randyzwitch / streamlit-folium

Streamlit Component for rendering Folium maps
https://folium.streamlit.app/
MIT License
475 stars 179 forks source link

Moving marker to click location #122

Open adolmajian opened 1 year ago

adolmajian commented 1 year ago

I'm trying to move a single marker on the map to where the user clicks on the map but I'm struggling. With every click (st_folium) the marker is moving to the previous click location instead of the current click location. What I am doing wrong here?

# State variables
if 'center' not in st.session_state:
    st.session_state.center = [45.503032, -73.566424]

if 'zoom' not in st.session_state:
    st.session_state.zoom = 15

if 'location' not in st.session_state:
    st.session_state.location = folium.Marker(st.session_state.center)

# Map creation
m = folium.Map(location=st.session_state.center, zoom_start=st.session_state.zoom)
fg = folium.FeatureGroup(name="Markers")
fg.add_child(st.session_state.location)

# When the user interacts with the map
map_state_change = st_folium(
      m,
      feature_group_to_add=fg,
      height=400,
      width='100%',
      returned_objects=['last_clicked', 'zoom', 'bounds', 'center'],
)

# If the interaction includes a click
if map_state_change['last_clicked']:
    loc = map_state_change['last_clicked']
    st.session_state.location = folium.Marker([loc['lat'], loc['lng']])
SirVectrex commented 12 months ago

I am currently struggling with the same issue.

Adding a button, that forces a zoom change is a work-around.

Were you able to find a better solution? @adolmajian

adolmajian commented 11 months ago

What I ended up doing is not relying on a click at all. I added a crosshair as text in my Streamlit app and some hacky markdown to position the crosshair in the center of the map. You can see the app and code at https://isochrone.streamlit.app/.