Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change (and change back) leaflet icon on click

I've gotten the icon to change on click, but I need it to change back to the original icon (not stay the new one) when a new icon is clicked.

For instance, say all of my icons are blue. When I click on an icon, I want it to change to a red icon. Then, when I click on a new icon, I want the previously clicked icon to change back to blue.

I can get it to work with mouseover and mouseout, but I really need it to work with click. I think I need to log a new click function, but I'm not sure how.

Here's what I currently have:

function clickFeature(e) {
        var layer = e.target;
        e.target.setIcon(stop);

        info.update(layer.feature.properties);
    }


    var geojson;

    /*function resetHighlight(e) {
        geojson.resetStyle(e.target);
        e.target.setIcon(arms);
        info.update();
    }*/

    function onEachFeature(feature, layer) {
        layer.on({
            click: clickFeature
        });
    }
    geojson = L.geoJson(crossingData, {

        pointToLayer: function (feature, latlng) {
            return L.marker(latlng, {icon: arms});
        },
        onEachFeature: onEachFeature

    }).addTo(map);
like image 278
user1855009 Avatar asked Aug 01 '13 14:08

user1855009


2 Answers

You can try to define seprate variable outside of function, that will hold currently clicked marker.

var clickedMarker;

function clickFeature(e) {
    if(clickedMarker) {
          clickedMarker.setIcon(arms);
    }
    var layer = e.target;
    e.target.setIcon(stop);
    clickedMarker = e.target;

    info.update(layer.feature.properties);
}
like image 119
Michał Krzemiński Avatar answered Nov 06 '22 07:11

Michał Krzemiński


You should get current icon for change to another one. Unfortunately L.marker has no getIcon() method, but you can access it via options.icon.

function clickFeature(e) {
    var layer = e.target;
    layer.setIcon(layer.options.icon == arms ? stop : arms);
}
like image 44
Mics Avatar answered Nov 06 '22 05:11

Mics