MapLibre GL: Add custom image to a map style

MapLibre GL (an open-source fork of Mapbox GL) allows adding images to a map style and using them for layers visualization.

In this code sample, we would like to show how images can be loaded from URL and used in layers specifications. The full version of the code sample you can find on JSFiddle.

1. Get an icon url

You can design your own map marker icon with the Marker Icon API playground or use any other icon.

2. Load image

Use Map.loadImage and Map.addImage to load an image to your map:

// getting an icon from Geoapify Icons API
// Explicitly set scaleFactor=2 in the call 
// and {pixelRatio: scale} to get better 
// Marker Icon quality with Mapbox GL
var scale=2;
map.loadImage(`https://api.geoapify.com/v1/icon/?icon=coffee&scaleFactor=${scale}&color=%23ff9999&size=large&type=awesome&apiKey=${YOUR_API_KEY}`, function(error, image) {
  if (error) throw error;
  map.addImage('rosa-pin', image, {pixelRatio: scale}); // 38x55px, shadow adds 5px (for scale eq 1)
});

3. Use image

When adding a layer of type symbol set an image as a icon-image layout parameter.

map.addLayer({
    'id': layerId,
    'type': 'symbol',
    'source': id,
    'layout': {
        'icon-image': 'rosa-pin',
        'icon-anchor': 'bottom',
        'icon-offset': [0, 5],
        'icon-allow-overlap': true
    }
});

Note, by default the icon anchor is center. So the center of your marker is attached to marker position. Change the icon-anchor (for example, to bottom for a pin icon) to change marker position. In addition, you need to set an icon-offset if the marker icon contains a shadow. For example, 5px for the icon provided in this code sample.