1

This is a follow up question to "Error changing marker icon when clicked in Leaflet". I want to highlight a marker when clicked but at the same time reset previously highlighted marker. I used the code below but there are some flaws in the logic which I could not correct it.

        var selectedLayer;
    function highlightSchool(e) {
        removeHighlight;
        var layer = e.target;
        layer.setIcon(highlightIcon);
        selectedLayer = layer;
    }

    function removeHighlight(e) {
        layer = e.target;
        if(selectedLayer!== layer){
            selectedLayer.setIcon(primaryIcon); 
        }

    }

    function onEachFeatureSchool(feature, layer) {
        layer.on({
            //mouseout: removeHighlight,
            click: highlightSchool
        });
    }

var schoolP = new L.GeoJSON.AJAX('data/schools.json', {pointToLayer:function(feature,latlng){ var str= "<h6><b>"+feature.properties.sch_name+", "+feature.properties.sch_loc+"</b><br>Primary Schools</h6>"; return L.marker(latlng,{icon: primaryIcon}).bindPopup(str);
}onEachFeature: onEachFeatureSchool});

    schoolP.addTo(mymap);

TomazicM
  • 25,601
  • 22
  • 29
  • 39
  • does https://gis.stackexchange.com/questions/54651/change-marker-icon-on-click-using-leaflet answer your question? – Ian Turton May 16 '23 at 07:55

1 Answers1

1

First reason why your code does not work as expected is the way you try to call function removeHighlight. To execute it, it should be at least removeHighlight(), but it would not work without parameter. So it should be removeHighlight(e).

Event if you correct this, removeHighlight would fail, since first time selectedLayer is undefined, so selectedLayer.setIcon(primaryIcon) would fail.

So relevant part of the code could then look something like this:

function highlightSchool(e) {
  var layer = e.target;
  removeHighlight(layer);
  layer.setIcon(highlightIcon);
  selectedLayer = layer;
}

function removeHighlight(layer) { if (selectedLayer && (selectedLayer !== layer)){ selectedLayer.setIcon(primaryIcon); }
}

TomazicM
  • 25,601
  • 22
  • 29
  • 39
  • Thanks @TomazicM. Yes, this works perfectly fine. I have implemented bit differently though. I used your previous answer (in another thread) in combination with the solution described in [https://plnkr.co/edit/aqiImS?p=preview&preview]. Anyway, it works now the way I wanted, so thank you so much. – user3072602 May 18 '23 at 00:44