Skip to content

Live geojson

image image image

Add live realtime data

Use realtime GeoJSON data streams to move a symbol on your map.

This source code of this example is adapted from the MapLibre GL JS example - Add live realtime data.

Uncomment the following line to install leafmap if needed.

1
# %pip install "leafmap[maplibre]"
1
2
3
import requests
import time
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
m = leafmap.Map(center=[0, 20], zoom=1, style="streets")
source = {
    "type": "geojson",
    "data": {"type": "Feature", "geometry": {"type": "Point", "coordinates": [0, 0]}},
}
m.add_source("drone", source)

layer = {
    "id": "drone",
    "type": "symbol",
    "source": "drone",
    "layout": {"icon-image": "rocket_15"},
}
m.add_layer(layer)
m
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def update_location(num_times, time_interval):
    url = "https://www.random.org/decimal-fractions/?num=2&dec=10&col=1&format=plain&rnd=new"
    for _ in range(num_times):
        response = requests.get(url)
        data = response.text
        data = data.strip().split("\n")
        # Takes the two random numbers between 0 and 1 and converts them to degrees
        lat, lon = float(data[0]) * 180 - 90, float(data[1]) * 180 - 90
        geojson = {
            "type": "Feature",
            "geometry": {"type": "Point", "coordinates": [lon, lat]},
        }
        m.set_data("drone", geojson)
        time.sleep(time_interval)
1
update_location(20, 0.5)