Rahulk2197 commited on
Commit
f543551
Β·
verified Β·
1 Parent(s): f9c3cbc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -20
app.py CHANGED
@@ -1,24 +1,52 @@
1
  import streamlit as st
2
  import requests
3
 
4
- def get_location():
5
- try:
6
- response = requests.get("https://ipinfo.io/json")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  data = response.json()
8
- return {
9
- "City": data.get("city"),
10
- "Region": data.get("region"),
11
- "Country": data.get("country"),
12
- "Location (Lat, Long)": data.get("loc"),
13
- "IP Address": data.get("ip"),
14
- }
15
- except Exception as e:
16
- return {"Error": str(e)}
17
-
18
- st.title("πŸ“ Find Your Location")
19
-
20
- st.write("This app fetches your location using your IP address.")
21
-
22
- if st.button("Get My Location"):
23
- location_data = get_location()
24
- st.json(location_data)
 
1
  import streamlit as st
2
  import requests
3
 
4
+ st.title("πŸ“ Get Your Device Location")
5
+
6
+ # Inject JavaScript to get location from the browser
7
+ st.write("Click the button below to get your device's location.")
8
+
9
+ get_location_js = """
10
+ <script>
11
+ navigator.geolocation.getCurrentPosition(
12
+ (position) => {
13
+ const coords = position.coords.latitude + "," + position.coords.longitude;
14
+ document.getElementById("location-data").value = coords;
15
+ document.getElementById("submit-btn").click();
16
+ },
17
+ (error) => {
18
+ alert("Geolocation not available. Please allow location access.");
19
+ }
20
+ );
21
+ </script>
22
+ """
23
+
24
+ # Hidden input field to store coordinates
25
+ st.markdown('<input type="hidden" id="location-data">', unsafe_allow_html=True)
26
+
27
+ # Create a form to capture location data
28
+ with st.form("location_form"):
29
+ location = st.text_input("Your Coordinates", key="location", disabled=True)
30
+ submitted = st.form_submit_button("Submit", key="submit-btn")
31
+
32
+ # Run the JavaScript when the user clicks the button
33
+ st.markdown(get_location_js, unsafe_allow_html=True)
34
+
35
+ # Reverse Geocoding using OpenStreetMap (Nominatim API)
36
+ def get_address(lat, lon):
37
+ url = f"https://nominatim.openstreetmap.org/reverse?format=json&lat={lat}&lon={lon}"
38
+ response = requests.get(url)
39
+ if response.status_code == 200:
40
  data = response.json()
41
+ return data.get("display_name", "Address not found")
42
+ return "Failed to fetch address"
43
+
44
+ # Display the location details
45
+ if submitted and location:
46
+ lat, lon = map(str.strip, location.split(","))
47
+ address = get_address(lat, lon)
48
+
49
+ st.success("Your Location Details:")
50
+ st.write(f"**Latitude:** {lat}")
51
+ st.write(f"**Longitude:** {lon}")
52
+ st.write(f"**Address:** {address}")