I have a multipart shapefile I am attempting to display on a map using Folium. Code is as follows:
JavaScript
x
48
48
1
import folium
2
import gdal
3
import geopandas as gpd
4
import branca.colormap as cm
5
6
gdf = gpd.read_file("field.shp")
7
8
def rank_colormap(gdf):
9
if gdf['RANK'] is 1.0:
10
return 'red'
11
if gdf['RANK'] is 2.0 or 3.0:
12
return 'orange'
13
if gdf['RANK'] is 4.0:
14
return 'gold'
15
if gdf['RANK'] is 5.0 or 6.0:
16
return 'yellow'
17
if gdf['RANK'] is 7.0:
18
return 'greenyellow'
19
if gdf['RANK'] is 8.0 or 9.0:
20
return 'lime'
21
elif gdf['RANK'] is 10.0:
22
return 'green'
23
24
#create map object
25
m = folium.Map(location=[49.112675, -104.104781], zoom_start=15)
26
folium.GeoJson(data=gdf, style_function=lambda feature: {
27
'fillColor': rank_colormap(gdf),
28
'color': 'black',
29
'weight': '0.5',
30
'fill': True,
31
'fill_opacity' : '1'
32
}).add_to(m)
33
tile = folium.TileLayer(
34
tiles = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
35
attr = 'Esri',
36
name = 'Esri Satellite',
37
overlay = False,
38
control = True
39
).add_to(m)
40
41
42
legendcolormap = cm.LinearColormap(colors=['red', 'orange', 'gold' ,'yellow', 'greenyellow', 'lime', 'green'], vmin=1, vmax=10)
43
legendcolormap.add_to(m)
44
45
46
#global tooltip
47
tooltip = 'Click For More Info'
48
The gdf currently looks like this I am attempting to map the color to corresponding “RANK” value:
However, my fillcolor is not correctly adjusting and is just remaining one color:
How do I correctly assign a colormap to my folium map?
Advertisement
Answer
Solved it:
JavaScript
1
31
31
1
def getcolor(feature):
2
if feature['properties']['RANK'] == 1.0:
3
return 'red'
4
if feature['properties']['RANK'] == 2.0:
5
return 'orange'
6
if feature['properties']['RANK'] == 3.0:
7
return 'orange'
8
if feature['properties']['RANK'] == 4.0:
9
return 'gold'
10
if feature['properties']['RANK'] == 5.0:
11
return 'yellow'
12
if feature['properties']['RANK'] == 6.0:
13
return 'yellow'
14
if feature['properties']['RANK'] == 7.0:
15
return 'greenyellow'
16
if feature['properties']['RANK'] == 8.0:
17
return 'lime'
18
if feature['properties']['RANK'] == 9.0:
19
return 'lime'
20
if feature['properties']['RANK'] == 10.0:
21
return 'green'
22
else:
23
return 'gray'
24
25
folium.GeoJson(gdf1, smooth_factor = 1, style_function = lambda feature: {
26
'fillColor': getcolor(feature),
27
'weight': 0,
28
'fillOpacity': 0.8,
29
}).add_to(fg1)
30
31