| |
|
|
| import streamlit as st |
| import streamlit.components.v1 as components |
|
|
| def streamlit_geolocation(): |
| """ |
| Custom implementation of streamlit-geolocation for Hugging Face Spaces |
| Returns location data if available |
| """ |
| |
| component_key = "geolocation_component" |
|
|
| |
| geolocation_html = """ |
| <div id="location-data" style="display: none;"></div> |
| <button |
| id="get-location" |
| onclick="getLocation()" |
| style="background-color: #ff4b4b; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;" |
| > |
| 📍 Get My Location |
| </button> |
| <p id="status" style="margin-top: 10px;"></p> |
| |
| <script> |
| function getLocation() { |
| document.getElementById('status').textContent = 'Getting location...'; |
| document.getElementById('get-location').disabled = true; |
| |
| if (navigator.geolocation) { |
| navigator.geolocation.getCurrentPosition( |
| function(position) { |
| const locationData = { |
| coords: { |
| latitude: position.coords.latitude, |
| longitude: position.coords.longitude, |
| accuracy: position.coords.accuracy |
| }, |
| timestamp: position.timestamp |
| }; |
| |
| document.getElementById('location-data').textContent = JSON.stringify(locationData); |
| document.getElementById('status').textContent = 'Location found! Updating...'; |
| |
| // Redirect with parameters |
| window.location.href = window.location.pathname + |
| '?lat=' + position.coords.latitude + |
| '&lon=' + position.coords.longitude; |
| }, |
| function(error) { |
| document.getElementById('status').textContent = 'Error: ' + error.message; |
| document.getElementById('get-location').disabled = false; |
| }, |
| { |
| enableHighAccuracy: true, |
| timeout: 10000, |
| maximumAge: 0 |
| } |
| ); |
| } else { |
| document.getElementById('status').textContent = 'Geolocation is not supported by this browser.'; |
| document.getElementById('get-location').disabled = false; |
| } |
| } |
| </script> |
| """ |
|
|
| |
| components.html(geolocation_html, height=100, key=component_key) |
|
|
| |
| if 'lat' in st.query_params and 'lon' in st.query_params: |
| try: |
| lat = float(st.query_params['lat']) |
| lon = float(st.query_params['lon']) |
| |
| |
| return { |
| 'coords': { |
| 'latitude': lat, |
| 'longitude': lon, |
| 'accuracy': 0 |
| }, |
| 'timestamp': None |
| } |
| except: |
| return None |
|
|
| return None |