Skip to content

Add a generated icon to the map

Replicates the MapLibre example Add a generated icon to the map. The symbol layer is YAML. Its icon is not a file but pixels the page computes, so it can’t be an images: entry. The layer starts hidden (visible: false); the page builds a 64×64 RGBA gradient, registers it with map.addImage, and shows the layer with <ml-map>’s setLayerVisibility.

A gradient square generated pixel by pixel
add-a-generated-icon-to-the-map.yaml
# yaml-language-server: $schema=https://docs.maplibre-yaml.org/schema/latest/map.schema.json
# Gallery twin of https://maplibre.org/maplibre-gl-js/docs/examples/add-a-generated-icon-to-the-map/
# The YAML half: the point and the symbol layer that draws it. Its icon is
# not a file — the page computes its pixels — so the layer starts hidden
# (`visible: false`) until add-a-generated-icon-to-the-map.js has added
# the image, rather than asking MapLibre for an image that doesn't exist yet.
type: map
id: add-a-generated-icon-to-the-map
config:
center: [0, 0]
zoom: 1
mapStyle: "https://demotiles.maplibre.org/style.json"
layers:
- id: points
type: symbol
visible: false
source:
type: geojson
location:
coordinates: [0, 0]
layout:
icon-image: gradient
add-a-generated-icon-to-the-map.js
// The JavaScript half: map.addImage() with raw pixels. A 64×64 RGBA buffer
// becomes the image "gradient" (red down, green across); then the layer
// the YAML declared hidden is shown through <ml-map>'s setLayerVisibility.
const mapEl = document.querySelector("ml-map");
mapEl.mapReady().then((map) => {
const width = 64;
const bytesPerPixel = 4; // red, green, blue, alpha
const data = new Uint8Array(width * width * bytesPerPixel);
for (let x = 0; x < width; x++) {
for (let y = 0; y < width; y++) {
const offset = (y * width + x) * bytesPerPixel;
data[offset + 0] = (y / width) * 255; // red
data[offset + 1] = (x / width) * 255; // green
data[offset + 2] = 128; // blue
data[offset + 3] = 255; // alpha
}
}
map.addImage("gradient", { width, height: width, data });
mapEl.setLayerVisibility("points", true);
});
  • Starting the layer hidden means MapLibre never asks for an image that doesn’t exist yet — no missing-image warning, no flash.
  • For an icon that is a file (PNG or SVG), use images: — see Display a remote SVG symbol.