Skip to content

59 create legend

image image image

Uncomment the following line to install leafmap if needed.

1
# !pip install -U leafmap
1
import leafmap.foliumap as leafmap

Create a built-in draggable legend. Specify the output parameter to save the legend as an HTML file.

1
2
3
4
5
6
leafmap.create_legend(
    title="NLCD Land Cover Type",
    builtin_legend="NLCD",
    draggable=True,
    output="NLCD_legend.html",
)

Create a built-in non-draggable legend. If the output parameter is not specified, the legend will be returned as an HTML string.

1
2
3
4
5
6
html = leafmap.create_legend(
    title="NLCD Land Cover Type",
    builtin_legend="NLCD",
    draggable=False,
    position="bottomright",
)
1
2
widget = leafmap.show_html(html)
widget
1
2
3
4
try:
    widget.close()
except:
    pass

Create a custom legend.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
legend_dict = {
    "10 Trees": "006400",
    "20 Shrubland": "ffbb22",
    "30 Grassland": "ffff4c",
    "40 Cropland": "f096ff",
    "50 Built-up": "fa0000",
    "60 Barren / sparse vegetation": "b4b4b4",
    "70 Snow and ice": "f0f0f0",
    "80 Open water": "0064c8",
    "90 Herbaceous wetland": "0096a0",
    "95 Mangroves": "00cf75",
    "100 Moss and lichen": "fae6a0",
}
1
2
3
4
5
6
leafmap.create_legend(
    title="ESA Land Cover Type",
    legend_dict=legend_dict,
    draggable=False,
    output="ESA_legend.html",
)

Customize the legend by specifying the style parameter.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
m = leafmap.Map()
m.add_basemap("ESA WorldCover 2021")

style = {
    "position": "fixed",
    "z-index": "9999",
    "border": "2px solid grey",
    "background-color": "rgba(255, 255, 255, 0.8)",
    "border-radius": "10px",
    "padding": "5px",
    "font-size": "14px",
    "bottom": "20px",
    "right": "5px",
}

m.add_legend(
    title="ESA Land Cover Type", legend_dict=legend_dict, draggable=False, style=style
)
m

Add a legend to the map.

1
2
3
4
m = leafmap.Map()
m.add_basemap("ESA WorldCover 2021")
m.add_legend(title="ESA Land Cover Type", builtin_legend="ESA_WorldCover")
m

Add legends to a split-view map. Make sure the draggable parameter is set to False.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
m = leafmap.Map(
    center=[40, -100],
    zoom=4,
    draw_control=False,
    measure_control=False,
    scale_control=False,
)
m.split_map(left_layer="ESA WorldCover 2021", right_layer="NLCD 2019 CONUS Land Cover")
m.add_legend(
    title="ESA Land Cover Type",
    builtin_legend="ESA_WorldCover",
    draggable=False,
    position="bottomleft",
    style={"bottom": "5px"},
)
m.add_legend(
    title="NLCD Land Cover Type",
    builtin_legend="NLCD",
    draggable=False,
    position="bottomright",
)
m