Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add a class to a Leaflet marker?

I'm using custom divIcons for my Leaflet markers. I want to add a border to whatever marker I click on, with some simple CSS:

.selectedMarker {
border: 10px solid gold;
}

However, the following with jQuery doesn't work:

$(marker).addClass('selectedMarker');

Then I tried to use Leaflet's own addClass() method. I tried to call use it in the following ways:

marker.addClass('selectedMarker');
L.addClass(marker, 'selectedMarker');
addClass(marker, 'selectedMarker');
DomUtil.addClass(marker, 'selectedMarker');

None of these work. How do I add the selectedMarker class to my marker?

like image 952
yesman Avatar asked Dec 03 '14 09:12

yesman


People also ask

How do you set a marker in leaflet?

Adding a Simple MarkerStep 1 − Create a Map object by passing a <div> element (String or object) and map options (optional). Step 2 − Create a Layer object by passing the URL of the desired tile. Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

How many markers can leaflet handle?

The Clusterer can handle 10,000 or even 50,000 markers (in chrome).


3 Answers

In 1.0 and 0.7 you can use L.DomUtil to add remove classes from a DOM element:

L.DomUtil.addClass(marker._icon, 'className');
L.DomUtil.removeClass(marker._icon, 'className');
like image 89
bgeo Avatar answered Oct 17 '22 21:10

bgeo


I have done it by adding a class to the marker with

var marker = L.marker(loc);
marker.on('click', function() {
    $(marker._icon).addClass('selectedMarker');
}

and then use the css

.leaflet-marker-icon.selectedMarker{
  //your css
}
like image 21
r8n5n Avatar answered Oct 17 '22 22:10

r8n5n


without using jQuery,

marker._icon.classList.add("className");
like image 18
Mujtaba Kably Avatar answered Oct 17 '22 22:10

Mujtaba Kably