I want to print some colorized polygons on a map with folium in python and I need some help. The problem I encounter is that I only get a single color for all of my polygons. Here is a part of my code I run in a loop:
import folium
from shapely.geometry import Polygon
def map_color_rsrp(rsrp):
if (int(rsrp) in range(-70, -50)):
return '#10FF00'
elif (int(rsrp) in range(-90, -70)):
return 'green'
elif (int(rsrp) in range(-110, -90)):
return 'blue'
elif (int(rsrp) in range(-130, -110)):
return '#FF7000'
else: # range(-150, -130)
return 'grey'
# create map
grid_map = folium.Map((51.443787, 7.262206), zoom_start=14)
# create FeatureGroups for RSRP & RSRQ
rsrp_grid_fg = folium.FeatureGroup(name="RSRP", overlay=True)
grid_poly_rows = [
[-78.2, [(7.251043000000002, 51.444325000000035), (7.251043000000002, 51.44462500000004), (7.251343000000002, 51.44462500000004), (7.251343000000002, 51.444325000000035)]],
[-89.3, [(7.251343000000002, 51.444325000000035), (7.251343000000002, 51.44462500000004), (7.251643000000002, 51.44462500000004), (7.251643000000002, 51.444325000000035)]],
[-113.7, [(7.251643000000002, 51.44402500000003), (7.251643000000002, 51.444325000000035), (7.2519430000000025, 51.444325000000035), (7.2519430000000025, 51.44402500000003)]],
[-112.3, [(7.251643000000002, 51.444325000000035), (7.251643000000002, 51.44462500000004), (7.2519430000000025, 51.44462500000004), (7.2519430000000025, 51.444325000000035)]],
[-133.7, [(7.2519430000000025, 51.44402500000003), (7.2519430000000025, 51.444325000000035), (7.252243000000003, 51.444325000000035), (7.252243000000003, 51.44402500000003)]]
]
for row in grid_poly_rows:
mean_rsrp = row[0]
rsrp_tooltip_str = str(mean_rsrp)
rsrp_color = map_color_rsrp(mean_rsrp)
style_ = {
'fillColor': rsrp_color,
'color': rsrp_color,
'weight': 1,
'fillOpacity': 0.5}
folium.GeoJson(Polygon(row[1]),
style_function=lambda x: style_,
tooltip=rsrp_tooltip_str
).add_to(rsrp_grid_fg)
rsrp_grid_fg.add_to(grid_map)
# add LayerControl
folium.LayerControl(collapsed=False).add_to(grid_map)
grid_map.save(outfile="grid.html")
I think I got something wrong with the style_function. Any advice is appreciated! Thanks in advance!
Cheers ninjab3s
I made it work! I found this post https://stackoverflow.com/a/53816162/13872164, which explains that the lambda style function is not executed immediately. The following changes made my code work:
for row in grid_poly_rows:
mean_rsrp = row[0]
rsrp_tooltip_str = str(mean_rsrp)
folium.GeoJson(Polygon(row[1]),
style_function=lambda x, mean_rsrp=mean_rsrp: {
'fillColor': map_color_rsrp(mean_rsrp),
'color': map_color_rsrp(mean_rsrp),
'weight': 1,
'fillOpacity': 0.5},
tooltip=rsrp_tooltip_str
).add_to(rsrp_grid_fg)
Next time Ill dig deeper before I post