6
votes

I would like to add a custom marker to my map. I am using a mapbox gl script.

The only documentation that I found related to this topic is this one https://www.mapbox.com/mapbox-gl-js/example/geojson-markers/.

I tried to customize given example and I managed to add a marker and modify it a little changing the size, but since I don't understand all the parameters, I don't know how to add my own marker. Is there any documentation that is more detailed?

Here is my code:

 <script>
    mapboxgl.accessToken = 'pk.eyJ1IjoiYWl3YXRrbyIsImEiOiJjaXBncnI5ejgwMDE0dmJucTA5aDRrb2wzIn0.B2zm8WB9M_qiS1tNESWslg';
    var map = new mapboxgl.Map({
        container: 'map', // container id
        style: 'mapbox://styles/aiwatko/cipo0wkip002ddfm1tp395va4', //stylesheet location
        center: [7.449932,46.948856], // starting position
        zoom: 14.3, // starting zoom
        interactive: true
    });       

    map.on('load', function () {
    map.addSource("markers", {
        "type": "geojson",
        "data": {
            "type": "FeatureCollection",
            "features": [{
                "type": "Feature",
                "geometry": {
                    "type": "Point",
                    "coordinates": [7.4368330, 46.9516040]
                },
                "properties": {
                    "title": "Duotones",
                    "marker-symbol": "marker",

                }
            }]
        }
    });

    map.addLayer({
        "id": "markers",
        "type": "symbol",
        "source": "markers",
        "layout": {
            "icon-image": "{marker-symbol}-15",
            "icon-size": 3
        }
    });
});
</script>

Thanks in advance!

Oktawia

1

1 Answers

6
votes

There are two ways to customize markers in Mapbox.

Raster Markers in Mapbox

See this link on Mapbox.com for Custom marker icons. That example shows how to use a .png as a marker.

SVG Markers in Mapbox

You are pretty close to modifying the icons, but take some time to familiarize yourself with the parameters.

The icon-image may be the harder one to understand. It takes the property "marker-symbol": "marker" from the GeoJson, and "icon-image": "{marker-symbol}-15", to create the final result of marker-15.

This brings up a further question: where/how are the markers defined?!?

The markers also come from Mapbox and are called Maki Icons. You can change the "marker-symbol" to aquarium or cafe to see the results.

From the Mapbox GL Style Reference

  • icon-size — Scale factor for icon. 1 is original size, 3 triples the size.
  • icon-image — A string with {tokens} replaced, referencing the data property to pull from.