Skip to content

Draw features

image image image

Draw features on the map

This notebook shows how to draw features on the map using the mapbox-gl-draw plugin.

Uncomment the following line to install leafmap if needed.

1
# %pip install "leafmap[maplibre]"
1
2
import os
import leafmap.maplibregl as leafmap

Add the default draw control.

1
2
3
m = leafmap.Map(center=[-100, 40], zoom=3, style="positron")
m.add_draw_control(position="top-left")
m

Only activate a give set of control.

1
from maplibre.plugins import MapboxDrawControls, MapboxDrawOptions
1
2
3
4
5
6
7
m = leafmap.Map(center=[-100, 40], zoom=3, style="positron")
draw_options = MapboxDrawOptions(
    display_controls_default=False,
    controls=MapboxDrawControls(polygon=True, line_string=True, point=True, trash=True),
)
m.add_draw_control(draw_options)
m

Load a GeoJSON FeatureCollection to the draw control.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
m = leafmap.Map(center=[-100, 40], zoom=3, style="positron")
geojson = {
    "type": "FeatureCollection",
    "features": [
        {
            "id": "abc",
            "type": "Feature",
            "properties": {},
            "geometry": {
                "coordinates": [
                    [
                        [-119.08, 45.95],
                        [-119.79, 42.08],
                        [-107.28, 41.43],
                        [-108.15, 46.44],
                        [-119.08, 45.95],
                    ]
                ],
                "type": "Polygon",
            },
        },
        {
            "id": "xyz",
            "type": "Feature",
            "properties": {},
            "geometry": {
                "coordinates": [
                    [
                        [-103.87, 38.08],
                        [-108.54, 36.44],
                        [-106.25, 33.00],
                        [-99.91, 31.79],
                        [-96.82, 35.48],
                        [-98.80, 37.77],
                        [-103.87, 38.08],
                    ]
                ],
                "type": "Polygon",
            },
        },
    ],
}
m.add_draw_control(position="top-left", geojson=geojson)
m

Retrieve the draw features.

1
m.draw_features_selected
1
m.draw_feature_collection_all