2
votes

I have a list with different locations. Everytime someone clicks on a location I remove the marker layer from my map and then a function is triggered which makes a new layer of markers with the same locations as before, only this time is uses a different icon for the selected location.

My problem is that I don't want to remove and add the layer, instead I just want to update the icon of the specific marker but I cannot find a way to access it.

Someone mentioned that this is possible through .eachLayer function but I cannot see how, since this one is to control the layers, not the markers.

markers = new L.featureGroup(); 


function updateMarker(locations, clickedID){
    //Adding all markers on map
    for (var i = 0; i < locations.length; i++) 
    {       
        //red marker for the selected location
        if (locations[i][2] == clickedID){
            marker = new L.marker([locations[i][0],locations[i][1]],{
                icon: redIcon})
                .bindPopup(locations[i][3]);
            markers.addLayer(marker);   
        }
        else{
            //add regular marker
            marker = new L.marker([locations[i][0],locations[i][1]])
                .bindPopup(locations[i][3])
                .addTo(map);
            markers.addLayer(marker);
        }


    } ;

    map.addLayer(markers);
}
1

1 Answers

3
votes

Without an example, what you want to achieve is not 100% clear.

However, if you want to manipulate markers (using setIcon() for example), it is much easier to keep an array of all your markers.

var markers = {};   // list of created markers

When you create a marker, you add it to your array

markers[theID] = L.marker();
map.addLayer(markers[theID]);

You can then modify your marker easily without having to scan your featureGroup.

markers[theID].setIcon();