randyzwitch / streamlit-folium

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

Feature group not removed from the map #163

Closed patrontheo closed 10 months ago

patrontheo commented 10 months ago

from #153 if you remove a dynamic feature group (setting feature_group_to_add to None), it is not removed from the map. I think it comes from here, where the removeLayer mewthod is called only if the feature group is not None.

Sample code:

import folium
import geopandas as gpd
import shapely
import streamlit as st

from streamlit_folium import st_folium

st.set_page_config(layout='wide', initial_sidebar_state='collapsed')
st.write('<style>div.block-container{padding-top:2rem;}</style>', unsafe_allow_html=True) # remove padding top

START_LOCATION = [37.7944347109497, -122.398077892527]
START_ZOOM = 17

if not 'feature_group' in st.session_state:
    st.session_state['feature_group'] = None

wkt1 = "POLYGON ((-122.399077892527 37.7934347109497, -122.398922660838 37.7934544916178, -122.398980265018 37.7937266504805, -122.399133972495 37.7937070646238, -122.399077892527 37.7934347109497))"

polygon_1 = shapely.wkt.loads(wkt1)

gdf1 = gpd.GeoDataFrame(geometry=[polygon_1]).set_crs(epsg=4326)

style_parcels1 = {'fillColor': '#1100f8', 'color': '#1100f8', 'fillOpacity': 0.13, 'weight': 2 }

polygon_folium1 = folium.GeoJson(data=gdf1, style_function=lambda x: style_parcels1)

map = folium.Map(
    location=START_LOCATION, zoom_start=START_ZOOM, tiles="OpenStreetMap", max_zoom=21
)

fg1 = folium.FeatureGroup(name="Parcels")
fg1.add_child(polygon_folium1)

def add_fg_to_ss(fg):
    st.session_state["feature_group"] = fg

def remove_fg_from_ss():
    st.session_state["feature_group"] = None

b1 = st.button("Add Feature Group", on_click=add_fg_to_ss, args=(fg1,))
b2 = st.button("Remove Feature Group", on_click=remove_fg_from_ss)

st_folium(
    map,
    width=800,
    height=450,
    returned_objects=[],
    feature_group_to_add=st.session_state['feature_group'],
    debug=False,
)