pythongeojsonfoliumindex-error

why do I get an Error in folium.GeoJson style_funtion?


I would like to plot coordinates with folium and fill the circles according the column "type".

I tried to do this according the example given here: https://python-visualization.github.io/folium/latest/user_guide/geojson/geojson_marker.html

Somehow it doesn't work for my code:

import geopandas
from shapely.geometry import Point
import folium


d = {'type': [1, 2], 'geometry': [Point(9.59, 49.29), Point(9.65, 49.35)]}
gdf = geopandas.GeoDataFrame(d, crs="EPSG:4326")

colors = ["yellow", "red"]

m = folium.Map(location=[51, 10], zoom_start=7, tiles="cartodb voyager")


folium.GeoJson(
    gdf,
    marker=folium.Circle(radius=10, fill_color="orange", fill_opacity=0.4, color="black", weight=1),
    style_function=lambda x: {
        "fillColor": colors[x['properties']['type']],
    }
).add_to(m)

m

I always get: IndexError: list index out of range

Can you please explain why this error occurs? Also I don't really understand what exactly happens in the style_function.


Solution

  • That's because you define only two colors (zero-based). So, colors[2] (for type 2) is triggering the IndexError. You can fix it this way :

        style_function=lambda x: {
            "fillColor": colors[x["properties"]["type"]-1], # substract 1
        }
    

    Note that you can also map the colors to the type of each location and then explore your data while passing the type as the color parameter :

    ( # you can store a folium.Map with `m = (`
        gdf.assign(type=gdf["type"].map(
            dict(enumerate(colors, start=1))).fillna("orange"))
           .explore(
               tiles="cartodb voyager",
               color="type",
               style_kwds={
                   "radius": 4,
                   "stroke": True,
                   "color": "black",
                   "weight": 1,
                   "fillOpacity": 1,
               },
               zoom_start=12,
               width=700, height=300,
           )
    )
    

    Output :

    enter image description here