Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import requests | |
| st.title("π Get Your Device Location") | |
| # Inject JavaScript to get location from the browser | |
| get_location_js = """ | |
| <script> | |
| navigator.geolocation.getCurrentPosition( | |
| (position) => { | |
| const coords = position.coords.latitude + "," + position.coords.longitude; | |
| document.getElementById("location-data").value = coords; | |
| document.getElementById("submit-btn").click(); | |
| }, | |
| (error) => { | |
| alert("Geolocation not available. Please allow location access."); | |
| } | |
| ); | |
| </script> | |
| """ | |
| # Hidden input field to store coordinates | |
| st.markdown('<input type="hidden" id="location-data">', unsafe_allow_html=True) | |
| # Create a form to capture location data | |
| with st.form("location_form"): | |
| location = st.text_input("Your Coordinates", key="location", disabled=True) | |
| submitted = st.form_submit_button("Submit") # Fixed: Removed 'key' argument | |
| # Run the JavaScript when the user clicks the button | |
| st.markdown(get_location_js, unsafe_allow_html=True) | |
| # Reverse Geocoding using OpenStreetMap (Nominatim API) | |
| def get_address(lat, lon): | |
| url = f"https://nominatim.openstreetmap.org/reverse?format=json&lat={lat}&lon={lon}" | |
| response = requests.get(url) | |
| if response.status_code == 200: | |
| data = response.json() | |
| return data.get("display_name", "Address not found") | |
| return "Failed to fetch address" | |
| # Display the location details | |
| if submitted and location: | |
| lat, lon = map(str.strip, location.split(",")) | |
| address = get_address(lat, lon) | |
| st.success("Your Location Details:") | |
| st.write(f"**Latitude:** {lat}") | |
| st.write(f"**Longitude:** {lon}") | |
| st.write(f"**Address:** {address}") | |