4

I have a geoJSON (10 points) that is drawn using an icon. I want to change the icon when I click on one of the points and then I want to change it back when clicking another point. I don't know how to change it back.

Can anyone help me?

I have this piece of code:

var icon1 = L.icon({
    iconUrl: 'img1.png',
    iconSize: [20,20]
});

var icon2 = L.icon({
    iconUrl: 'img2.png',
    iconSize: [20,20]
});

function clickFeature(e) {
   var layer = e.target;
   layer.setIcon(layer.options.icon = icon2);
}

function onEachFeature (feature, layer){
    layer.on({
        click: clickFeature,
    })
};

var pointsJSON = L.geoJson(points,{    
        pointToLayer: function (feature, latlng) {    
        return L.marker(latlng, {icon: icon1});
    },    
    onEachFeature: onEachFeature
    }   
).addTo(map);

1 Answer 1

3

Not tested, but something like this should work

var oldLayer = ""; // to start, declare an empty variable outside of the function scope
function clickFeature(e) {
   var layer = e.target;
   layer.setIcon(layer.options.icon = icon2);

   // only attempt to change oldLayer icon back to original if oldLayer defined
   if (oldLayer) oldLayer.setIcon(layer.options.icon = icon1);
   // keep a reference to switch the icon back on the next click
   oldLayer = layer;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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