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);
1

1 Answer 1

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); 
  }       
}
1
  • 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 [plnkr.co/edit/aqiImS?p=preview&preview]. Anyway, it works now the way I wanted, so thank you so much. May 18, 2023 at 0:44

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.