python-visualization / folium

Python Data. Leaflet.js Maps.
https://python-visualization.github.io/folium/
MIT License
6.94k stars 2.23k forks source link

GeoJson style is not being applied correctly #1932

Closed ocefpaf closed 7 months ago

ocefpaf commented 7 months ago

Describe the bug

Both in a loop or using a GeoDataframe, only the last style is applied to all geometries. We can see that in our docs:

Screenshot from 2024-04-16 21-23-04

To Reproduce

https://python-visualization.github.io/folium/latest/user_guide/geojson/geopandas_and_geo_interface.html

I also believe https://github.com/python-visualization/folium/issues/1608 is related.

Expected behavior We expect each geometry to have its own color defined by the style column.

Environment (please complete the following information):

Additional context In a loop one can "hack" this problem by assigning a unique value using exec (note recommended though).

import folium

m = folium.Map()
for k, glider in gdf.iterrows():
    exec(f"style_function = lambda x: {glider['style']}")  # hack it to make it work
    # style_function = lambda x: glider['style']  # shows the bug
    folium.GeoJson(
        data=glider["geometry"],
        style_function=style_function,
    ).add_to(m)
m

Possible solutions

I'll investigate more and see if I can come up with something. I did try with latest branca and folium and this is not solved yet.

ocefpaf commented 7 months ago

OK. We are hitting https://docs.python-guide.org/writing/gotchas/#late-binding-closures :-/ I'll see what we can do. At least we should amend the docs.

Update. The geopandas style column example has been broken for a while (since v0.9.0) and is unrelated to the late binding issue in the loop. It is likely due to https://github.com/python-visualization/folium/pull/1058

Options:

Conengmo commented 6 months ago

Thanks for addressing this issue @ocefpaf!