Skip to content

Instantly share code, notes, and snippets.

@ryanhamley
Last active May 12, 2024 03:35
Show Gist options
  • Save ryanhamley/3d6844349ae27cae3a087b028228f8cf to your computer and use it in GitHub Desktop.
Save ryanhamley/3d6844349ae27cae3a087b028228f8cf to your computer and use it in GitHub Desktop.
This gist shows how to use an <svg> element as an icon-image for a Mapbox GL symbol layer
// How to add an SVG as a symbol layer's icon image: https://github.com/mapbox/mapbox-gl-js/issues/5529#issuecomment-340011876
// Also see here: https://stackoverflow.com/a/11765731/2748013 (we need the data url stuff for the image src)
// NOTE: Importing SVGs requires an inline module loader such as https://github.com/webpack-contrib/svg-inline-loader
import template from './templates/marker.svg';
const width = 20;
const height = 40;
const img = new Image(width, height);
// map is your Mapbox GL map object
img.onload = () => map.addImage('marker', img);
img.src = `data:image/svg+xml;charset=utf-8,${template}`;
map.addLayer({
id: 'my-marker',
type: 'symbol',
source: {
type: 'geojson',
data: {
type: "FeatureCollection",
features: [{
type: "Feature",
geometry: {
type: "Point",
coordinates: [0,0]
}
}]
}
},
layout: {
'icon-image': 'marker'
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment