Tourist-Location-Analyzer / streamlit-geolocation.py
Neylton's picture
Rename streamlit_geolocation.py to streamlit-geolocation.py
3f14d9b verified
# streamlit_geolocation.py
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
"""
# Create a unique key for the component
component_key = "geolocation_component"
# HTML/JavaScript for location detection
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>
"""
# Render the component
components.html(geolocation_html, height=100, key=component_key)
# Check URL parameters for location data
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 location data in the expected format
return {
'coords': {
'latitude': lat,
'longitude': lon,
'accuracy': 0 # Default accuracy
},
'timestamp': None # No timestamp available from URL parameters
}
except:
return None
return None