简体   繁体   中英

Leaflet - add class to marker icon on click

I have a simple leaflet map and some markers on it. To give the user a better experience i want to highlight a clicked marker. The best and simplest would be if i could just add an additional class to the clicked marker to work on css with it. But i dont know how and all i found wasn't answering my question or i just didn't understood it.

Javascript

//Set the marker icon

    var markerIcon = L.vectorIcon({
            className: 'markerIcon',
            svgHeight: 30,
            svgWidth: 30,
            shape: {r: '15', cx: '15', cy: '15'},
            style: {
                fill: '#73B0E1'
            }
    });


//Populate the map with markers

    var markers = L.markerClusterGroup({});
    if(mapID == 'mapPublic') {
        markers.addLayer(L.marker([50, 8], {icon: markerIcon})).on('click', onClick);
        markers.addLayer(L.marker([50, 8.1], {icon: markerIcon})).on('click', onClick);
        markers.addLayer(L.marker([50, 8.2], {icon: markerIcon})).on('click', onClick);
        markers.addLayer(L.marker([50.1, 8.1], {icon: markerIcon})).on('click', onClick);
    }

    map.addLayer(markers);


//Onclick Function for the markers

    function onClick() {}

How can i add a second class to the marker to work in css with it? I allready tried this.classList.add('activeMarker') but it didn't worked, i think because of leaflets marker logic.

The marker isn't a DOM object so it's no good trying to add classes to it.

If you're trying to style the icon, you could use

function onClick(e) {

e.layer._icon.classList.add('activemarker');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM