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.
In [1]:
Copied!
# %pip install "leafmap[maplibre]"
# %pip install "leafmap[maplibre]"
In [2]:
Copied!
import numpy as np
import leafmap.maplibregl as leafmap
import numpy as np
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!
# 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
# 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
Failed to retrieve the MapTiler style. Defaulting to 'dark-matter' style.