1
votes

I need to add markers to a mapboxgl map using GeoJSON data I get via AJAX. I add the GeoJSON layer this way:

    geoJSONSource = new mapboxgl.GeoJSONSource({
        data: geodata
    });

    map.addSource('markers', geoJSONSource);
    map.addLayer({
        "id": "markers",
        "interactive": true,
        "type": "symbol",
        "source": "markers",
        "layout": {
            "icon-image": "{marker-symbol}-15", // stuff in {} gets replaced by the corresponding value
            "icon-allow-overlap": true,
            "icon-size": 1 // size of the icon
        }
    });

In the GeoJSON data itself, I set each feature to have the property 'marker-symbol' to 'rocket' in a loop before I add the GeoJSON to the map. However, what I need are small, circular images for each point, not a rocket. I would like to set the points to a small, circular image of one of three colors, depending on data contained in the GeoJSON. I plan to pick the svg image in a loop before I add the GeoJSON to the map.

How do I add a custom icon-image? It seems that even if I type gibberish for the icon-image field, the rocket image from Mapbox's pre-made marker symbols gets loaded. Otherwise, how do I add a custom marker-symbol?

I am using the streets-v8 mapbox style; I tried experimenting with making my own styles to access custom images for markers according to this link:

https://www.mapbox.com/help/custom-markers/#use-images-in-mapbox-gl-js

But I couldn't figure it out.

1

1 Answers

2
votes

The marker icons are loaded based on the current sprite sheet set in the style.

To load a custom icon-image, you need to specify a custom sprite json file in your style.json. Here is the corresponding github discussion with details: https://github.com/mapbox/mapbox-gl-js/issues/822

Here is an example of using custom sprites: http://codepen.io/znak/pen/PqOEyV

The map uses a custom style defined in a file called customstyle.json:

var map = new mapboxgl.Map({
    container: 'map',
    center: center,
    zoom: 8,
    style: 'http://www.lenart.pl/assets/codepen/customstyle.json'
});

where customstyle.json refers to a customsprite.json

"sprite": "http://www.lenart.pl/assets/codepen/customsprite",

customsprite.json specifies how to crop the corresponding PNG spritesheet located here:

http://www.lenart.pl/assets/codepen/customsprite.png

You can also use this utility: https://github.com/mapbox/spritezero-cli to generate the sprite json and the corresponding png spritesheet out of a directory full of SVG files.