Getting user location & updating session state

My app relies on getting the users live location. I couldn’t find anything built in to do this so am using some html and javascript to get the location. I am able to print the location from the html, but I cannot figure out how to get these variables into the rest of my app. I have been trying to update the session state through java but that also doesn’t seem to work.

def get_live_location():
    js_code = """
    <script>
    navigator.geolocation.getCurrentPosition(
        (position) => {
            const latitude = position.coords.latitude;
            const longitude = position.coords.longitude;
            const accuracy = position.coords.accuracy;
            document.getElementById("lat").innerText = latitude.toFixed(5);
            document.getElementById("lon").innerText = longitude.toFixed(5);
            document.getElementById("acc").innerText = accuracy.toFixed(2);
            document.querySelector('input[name="latitude"]').value = latitude.toFixed(5);
            document.querySelector('input[name="longitude"]').value = longitude.toFixed(5);
        },
        (error) => {
            console.error("Error Code = " + error.code + " - " + error.message);
        }
    );
    </script>
    <div>
        <p>Latitude: <span id="lat">0</span></p>
        <p>Longitude: <span id="lon">0</span></p>
        <p>Accuracy: <span id="acc">0</span> meters</p>
        <input type="hidden" name="latitude">
        <input type="hidden" name="longitude">
    </div>
    html(js_code)
    latitude = st.session_state.get("latitude", 0)
    longitude = st.session_state.get("longitude", 0)
     return 
    """
    streamlit.components.v1.html(js_code)
    latitude = st.session_state.get("latitude", 0)
    longitude = st.session_state.get("longitude", 0)

I call the script here and try to pull the info from the session state:

stop_data_service = st.session_state["processed_data"]["stop_data_service"]

if "latitude" not in st.session_state:
    st.session_state["latitude"] = bozeman_coords[0]
if "longitude" not in st.session_state:
    st.session_state["longitude"] = bozeman_coords[1]

# Display the initial values
st.write(f"Initial Latitude: {st.session_state['latitude']}, Initial Longitude: {st.session_state['longitude']}")

get_live_location()

live_lat = float(st.session_state["latitude"])
live_long = float(st.session_state["longitude"])
live_location = [live_lat, live_long] if live_lat and live_long else None

# Debug live location values
st.write(f"Live Latitude: {st.session_state['latitude']}, Live Longitude: {st.session_state['longitude']}")

debugging post

  • Streamlit 1.35.0
    -running local with pip

I found this app that also uses location services, I’ll see if I can copy it over, but it uses old streamlit version: locationInfo/location.py at main · OMGToFo/locationInfo · GitHub

1 Like

I’m about to try this:

Seems promising.