2

I use the following code in order to change the fillColor of a marker within my leaflet-client, as suggested on this post: https://gis.stackexchange.com/a/124928/20297

var marker = marker = L.circleMarker(latlng, myMarkerOptions).addTo(map);
marker.valueOf()._icon.style.fillColor = 'green'

However when I execute this, I get the following error:

Cannot read property 'style' of undefined

I also tried to directly change the markers color:

marker.fillColor = 'green'

which simply does absolutely nothing.

My browser is an Opera 66. However I also checked FireFox to no avail.

2 Answers 2

3

If you want to change fill color of L.circleMarker dynamically, you can use the setStyle method, inherited from the L.Path class.

To change marker fill color to green:

marker.setStyle({fillColor: 'green'});

The example you are referring to is for regular L.marker marker with user defined icon. It's also not politically correct since it uses internal object properties that might change from version to version. Politically correct method for changing icon background color would be to use className option of L.icon instance.

1
  • Your edit turned this answer into a treasure. I was sure relying on the internals is a bad thing, however I couldn´t find any resource to set the color once the marker was created. Thank you. Commented Feb 10, 2020 at 19:46
1

For change color circleMarker use NameCircle.setStyle({color: 'color name'});

Like this https://jsfiddle.net/magi2109/xd3Lmoqb/

circleMarker

circle2 = L.circleMarker([5,8]  ).addTo(map);
    
circle = L.circleMarker([2,1] ).addTo(map);
 
circle.setStyle({color: 'green'});

circle2.setStyle({color: 'red'});

Not the answer you're looking for? Browse other questions tagged or ask your own question.