Skip to content

Add image generated

image image image

Add a generated icon to the map

This source code of this example is adapted from the MapLibre GL JS example - Add a generated icon to the map.

Uncomment the following line to install leafmap if needed.

1
# %pip install "leafmap[maplibre]"
1
2
import numpy as np
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
37
38
39
40
41
42
43
44
45
# Generate the icon data
width = 64  # The image will be 64 pixels square
height = 64
bytes_per_pixel = 4  # Each pixel is represented by 4 bytes: red, green, blue, and alpha
data = np.zeros((width, width, bytes_per_pixel), dtype=np.uint8)

for x in range(width):
    for y in range(width):
        data[y, x, 0] = int((y / width) * 255)  # red
        data[y, x, 1] = int((x / width) * 255)  # green
        data[y, x, 2] = 128  # blue
        data[y, x, 3] = 255  # alpha

# Flatten the data array
flat_data = data.flatten()

# Create the image dictionary
image_dict = {
    "width": width,
    "height": height,
    "data": flat_data.tolist(),
}

m = leafmap.Map(center=[0, 0], zoom=1, style="streets")
m.add_image("gradient", image_dict)
source = {
    "type": "geojson",
    "data": {
        "type": "FeatureCollection",
        "features": [
            {"type": "Feature", "geometry": {"type": "Point", "coordinates": [0, 0]}}
        ],
    },
}

layer = {
    "id": "points",
    "type": "symbol",
    "source": "point",
    "layout": {"icon-image": "gradient"},
}

m.add_source("point", source)
m.add_layer(layer)
m