Returning Latitude, Longitude values from folium map on mouse click to python script (streamlit webapp)

Viewed 3340

I am writing a webapp where the user will click on the map and the latitude, longitude will be returned to the python script. the webapp is written on streamlit and for the map I am using folium. Currently, I used folium.LatLngPopup() to get the on click lat long of the clicked location, but I am very confused how to retrieve the values in my python script for further processing.

This is how it looks currently:

This is how it looks currently

#code snippet

import streamlit as st
from streamlit_folium import folium_static
import folium
m = folium.Map()
m.add_child(folium.LatLngPopup())
folium_static(m)

There might not be a native solution to it but any workaround will be appreciated!

2 Answers

If you can directly use the value instead of assigning it, you can just use map['last_clicked']['lat'] and map['last_clicked']['lng'] where map is defined. For example here I just print every location's lat/lng, but instead of just returning them, in a function you can do any operation you need:

import folium as fl
from streamlit_folium import st_folium
import streamlit as st

def get_pos(lat,lng):
    return lat,lng

m = fl.Map()

m.add_child(fl.LatLngPopup())

map = st_folium(m, height=350, width=700)


data = get_pos(map['last_clicked']['lat'],map['last_clicked']['lng'])

if data is not None:
    st.write(data)

I recently encountered the same problem to get the latitude and longitude then print it or save the values to a variable. Apparently, I found out the usual streamlit is static as I tried to create a streamlit.button which is supposed to add 1 to variable counter if clicked. Result: the variable counter is printed as 1, regardless how many I clicked.

To be able to take the input, the streamlit component should be 'bi-directional'. I might not be able to explain it clearly as I am still newb both in python or in javascript, but in short it suppose to listen to the change in the values.

The solution is to create the bi-directional component and later I found this awesome repo streamlit-light-leaflet. To run it, just follow along the README.md. Assuming you already install streamlit in the virtual env, do the npm install and npm run start. Then run the 'streamlit run file.py' in different terminal/command line. Click the url from the terminal where you run the streamlit.

If the map doesn't show, go to my_component/frontend/src/index.tsx and put your mapbox.com accessToken. To get the accessToken, you should sign up first to mapbox.com. It would be best practice to use .env and call your mapbox accessToken from there, to keep the code cleaner.

Related