Skip to content

Center on symbol

image image image

Center the map on a clicked symbol

This source code of this example is adapted from the MapLibre GL JS example - Center the map on a clicked symbol.

Uncomment the following line to install leafmap if needed.

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

To run this notebook, you will need an API key from MapTiler. Once you have the API key, you can uncomment the following code block and replace YOUR_API_KEY with your actual API key. Then, run the code block code to set the API key as an environment variable.

1
2
# import os
# os.environ["MAPTILER_KEY"] = "YOUR_API_KEY"
 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=[-90.96, -0.47], zoom=7.5, style="streets")
image = "https://maplibre.org/maplibre-gl-js/docs/assets/custom_marker.png"
m.add_image("custom-marker", image)
source = {
    "type": "geojson",
    "data": {
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "properties": {},
                "geometry": {
                    "type": "Point",
                    "coordinates": [-91.395263671875, -0.9145729757782163],
                },
            },
            {
                "type": "Feature",
                "properties": {},
                "geometry": {
                    "type": "Point",
                    "coordinates": [-90.32958984375, -0.6344474832838974],
                },
            },
            {
                "type": "Feature",
                "properties": {},
                "geometry": {
                    "type": "Point",
                    "coordinates": [-91.34033203125, 0.01647949196029245],
                },
            },
        ],
    },
}
m.add_source("points", source)
layer = {
    "id": "symbols",
    "type": "symbol",
    "source": "points",
    "layout": {"icon-image": "custom-marker"},
}
m.add_layer(layer)
m
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
output = widgets.Output()


def log_lng_lat(lng_lat):
    with output:
        output.clear_output()
        print(lng_lat.new)
        m.fly_to(lng_lat.new["lng"], lng_lat.new["lat"])


m.observe(log_lng_lat, "clicked")
output