Mapbox GL JS Change the color from the default marker
Asked Answered
A

5

10

I’m starting to loose my mind.

According to Mapbox API I should be able to change the default marker color but I didn't find any exemple in the documentation that doesn't use custom markers and the most likely syntax doesn't work.

I am using mapbox-gl-js/v0.44.2

var marker = new mapboxgl.Marker({ "color": "#b40219" })
                .setLngLat([0, 0])
                .addTo(map);

With this code, the map is shown without the marker and if I remove the color option the marker does display correctly but with the wrong color.

Any suggestion to where I messed up ?

Aquarelle answered 17/6, 2018 at 18:39 Comment(0)
A
6

Support for custom colors when using the default Marker SVG element is available since v0.45.0, you are using v0.44.2.

Release notes:

https://github.com/mapbox/mapbox-gl-js/releases

Afire answered 17/6, 2018 at 21:25 Comment(1)
The syntax is correct const marker = new mapboxgl.Marker({ "color": "#b40219" })Nnw
M
9

Screw jQuery

setMarkerColor(marker, color) {
      let markerElement = marker.getElement();
      markerElement
        .querySelectorAll('svg g[fill="' + marker._color + '"]')[0]
        .setAttribute("fill", color);
      marker._color = color;
    },
Moniz answered 5/2, 2021 at 17:52 Comment(1)
This code changes color of the marker's shade if previous color is #000000: i.sstatic.net/3pILu.pngOuachita
A
6

Support for custom colors when using the default Marker SVG element is available since v0.45.0, you are using v0.44.2.

Release notes:

https://github.com/mapbox/mapbox-gl-js/releases

Afire answered 17/6, 2018 at 21:25 Comment(1)
The syntax is correct const marker = new mapboxgl.Marker({ "color": "#b40219" })Nnw
B
4

And if you need to change the color of the default marker on the fly you may use this kind of function (used jQuery to get element's children):

function setMarkerColor(marker, color) {
    var $elem = jQuery(marker.getElement());
    $elem.find('svg g[fill="' + marker._color + '"]').attr('fill', color);
    marker._color = color;
}
Bunker answered 10/12, 2018 at 9:17 Comment(1)
I've just copied and pasted it and works perfectly. Thanks.Dichlorodiphenyltrichloroethane
W
1

when setting up the marker, put the color in the brackets:

new mapboxgl.Marker({ "color": "#b40219" }) //this changes color to a dark red// .setLngLat([-74.5, 40]) .addTo(map);

Wardieu answered 3/2, 2022 at 17:40 Comment(0)
S
0
marker = new mapboxgl.Marker({
        color: $parameters.UpdatedMarkerColor,
        draggable: false
    });
Sabian answered 12/11, 2021 at 11:46 Comment(1)
Please consider adding a brief explanation of how and why this solves the problem. This will help readers to better understand your solution.Corsetti

© 2022 - 2024 — McMap. All rights reserved.