Update a feature in realtime
Change an existing feature on your map in real-time by updating its data.
This source code of this example is adapted from the MapLibre GL JS example - Update a feature in realtime.
Uncomment the following line to install leafmap if needed.
In [1]:
Copied!
# %pip install "leafmap[maplibre]"
# %pip install "leafmap[maplibre]"
In [2]:
Copied!
import time
import geopandas as gpd
import leafmap.maplibregl as leafmap
import time
import geopandas as gpd
import leafmap.maplibregl as leafmap
In [3]:
Copied!
# import os
# os.environ["MAPTILER_KEY"] = "YOUR_API_KEY"
# import os
# os.environ["MAPTILER_KEY"] = "YOUR_API_KEY"
In [4]:
Copied!
m = leafmap.Map(center=[-122.019807, 45.632433], zoom=14, pitch=60, style="3d-terrain")
m
m = leafmap.Map(center=[-122.019807, 45.632433], zoom=14, pitch=60, style="3d-terrain")
m
An API key is required to use the 3D terrain feature.
In [5]:
Copied!
url = "https://maplibre.org/maplibre-gl-js/docs/assets/hike.geojson"
gdf = gpd.read_file(url)
coordinates = list(gdf.geometry[0].coords)
print(coordinates[:5])
url = "https://maplibre.org/maplibre-gl-js/docs/assets/hike.geojson"
gdf = gpd.read_file(url)
coordinates = list(gdf.geometry[0].coords)
print(coordinates[:5])
[(-122.019807, 45.632433), (-122.019767, 45.632453), (-122.01971, 45.632472), (-122.01971, 45.632505), (-122.019739, 45.632531)]
In [6]:
Copied!
source = {
"type": "geojson",
"data": {
"type": "Feature",
"geometry": {"type": "LineString", "coordinates": [coordinates[0]]},
},
}
m.add_source("trace", source)
layer = {
"id": "trace",
"type": "line",
"source": "trace",
"paint": {"line-color": "yellow", "line-opacity": 0.75, "line-width": 5},
}
m.add_layer(layer)
m.jump_to({"center": coordinates[0], "zoom": 14})
m.set_pitch(30)
source = {
"type": "geojson",
"data": {
"type": "Feature",
"geometry": {"type": "LineString", "coordinates": [coordinates[0]]},
},
}
m.add_source("trace", source)
layer = {
"id": "trace",
"type": "line",
"source": "trace",
"paint": {"line-color": "yellow", "line-opacity": 0.75, "line-width": 5},
}
m.add_layer(layer)
m.jump_to({"center": coordinates[0], "zoom": 14})
m.set_pitch(30)
In [7]:
Copied!
for coord in coordinates:
time.sleep(0.005)
source["data"]["geometry"]["coordinates"].append(coord)
m.set_data("trace", source["data"])
m.pan_to(coord)
for coord in coordinates:
time.sleep(0.005)
source["data"]["geometry"]["coordinates"].append(coord)
m.set_data("trace", source["data"])
m.pan_to(coord)