19
votes

Is there a way to change a mapbox-gl-js icon-image color?

This code taken from https://www.mapbox.com/mapbox-gl-js/example/geojson-markers/ won't change the marker color to red

map.addLayer({
    "id": "markers",
    "type": "symbol",
    "source": "markers",
    "layout": {
        "icon-image": "{marker-symbol}-15",
        "text-field": "{title}",
        "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
        "text-offset": [0, 0.6],
        "text-anchor": "top"
    },
    "paint": {
        "text-size": 12,
        "icon-color" : "#ff0000"
    }
});

I've tried all the options listed in the official documentation

3
Same issue can't figure it out also, maybe create a ticket on github?Gert Cuykens
lol I just realised you did hahaGert Cuykens

3 Answers

8
votes

The Problem is MapBox only allows you to color icons which are in the SDF (signed distance function) format.

icon-color The color of the icon. This can only be used with sdf icons.

Here is a small documentation about it. Like the GitHub post says it's limited for only one color. Getting a sdf file out of a png file is pretty easy in MapBox.

The documentation of the addImage function tells you that you can add an optional options paramater which can contain sdf and pixelRatio.

So all you have to do is something like this:

        map.loadImage(imageURL, function(error0, image0) {
            if (error0) throw error0;
            map.addImage("image", image0, {
                "sdf": "true"
            });

            map.addLayer({
                "id": "Layer1",
                "type": "symbol",
                "source": "places",
                "layout": {
                    "icon-image": "image",
                    "icon-allow-overlap": true,
                },
                "paint": {
                    "icon-color": "#00ff00",
                    "icon-halo-color": "#fff",
                    "icon-halo-width": 2
                }
            });
        });
8
votes

I found a answer. You need sdf icons specifically for it to work.

https://github.com/mapbox/mapbox-gl-js/issues/1594

Unfortunately we don't have a turnkey solution for generating sdf icons but you can see an example of how its done in the maki project

https://github.com/mapbox/maki/blob/mb-pages/sdf-render.js

Updated by @yurik: The above link no longer works, probably refers to https://github.com/mapbox/maki/blob/b0060646e28507037e71edf049a17fab470a0080/sdf-render.js

https://github.com/mapbox/mapbox-gl-js/issues/161

2
votes

You could also use your own pre-colored external icons (or generate colored ones on the fly) as icon-image if you use map.loadImage() and map.addImage() first.

Examples:

Add an icon to the map

Add a generated icon to the map