Skip to content

Animate point along route

image image image

Animate a point along a route

This source code of this example is adapted from the MapLibre GL JS example - Animate a point along a route.

Uncomment the following line to install leafmap if needed.

1
# %pip install "leafmap[maplibre]"
1
2
3
import time
import requests
import leafmap.maplibregl as leafmap

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
m = leafmap.Map(center=[-100, 40], zoom=3, style="streets")
url = "https://github.com/opengeos/datasets/releases/download/us/arc_with_bearings.geojson"
geojson = requests.get(url).json()
bearings = geojson["features"][0]["properties"]["bearings"]
coordinates = geojson["features"][0]["geometry"]["coordinates"][:-1]
m.add_geojson(geojson, name="route")

origin = [-122.414, 37.776]
destination = [-77.032, 38.913]

point = {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "properties": {},
            "geometry": {"type": "Point", "coordinates": origin},
        }
    ],
}
source = {"type": "geojson", "data": point}
m.add_source("point", source)
layer = {
    "id": "point",
    "source": "point",
    "type": "symbol",
    "layout": {
        "icon-image": "airport_15",
        "icon-rotate": ["get", "bearing"],
        "icon-rotation-alignment": "map",
        "icon-overlap": "always",
        "icon-ignore-placement": True,
    },
}
m.add_layer(layer)
m
1
2
3
4
5
for index, coordinate in enumerate(coordinates):
    point["features"][0]["geometry"]["coordinates"] = coordinate
    point["features"][0]["properties"]["bearing"] = bearings[index]
    m.set_data("point", point)
    time.sleep(0.05)