Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change divIcon className on click?

I have a leaflet map with several markers on it. On click on a marker this one should get highlighted. I use divIcons and want to change the whole icon or the className of it, both would work for me. At the moment i'm just changing the class of the created div in the html tree to highlight it. This works great, but i ue a marker clusterer. Therefore the divs get created and dumped on and on again and my highlight class dissapears at each clustering.

Markers:

var markerIcon = L.divIcon({
   className: 'marker--default',
   html: "15",
   iconAnchor: [20, 20]
});
var markerIconActive = L.divIcon({
    className: 'marker--state--active',
    html: "15",
    iconAnchor: [20, 20]
});

Integration of Marker:

var markers = L.markerClusterGroup({});

markers.addLayer(L.marker([50.919523, 6.940621], {icon: markerIcon})).on('click', onClick);

map.addLayer(markers);

Clickevent:

function onClick(e) {
   e.target.setIcon(markerIconActive);
}

Note: It doesn't work. I get the error "e.target.setIcon is not a function". After reading the documentary it seems that there is no setIcon method for divIcons. As said it would be working for me too if just the className get changed, but i don't know how to change this one.

Documentation:

https://leafletjs.com/reference-1.4.0.html#divicon

like image 296
Flo Avatar asked Dec 17 '25 21:12

Flo


1 Answers

Instead of trying to access the functions / properties via e.target.<function> use e.<function> or this.<function>:

function onClick(e) {
   e.setIcon(markerIconActive);
}

alternatively, you can access it through e.layer:

function onClick(e) {
   let marker = e.layer;

   marker.setIcon(markerIconActive);
}

Reading Material

Is there a way to click on any map marker and retrieve the marker's lat/lng (or array index)?

like image 69
Script47 Avatar answered Dec 19 '25 13:12

Script47



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!