Cant remove markers from leaflet map. Not using layers

Just discovered Leafletjs and loving it. I have been trying to remove all my makers when my json is empty or invalid and I just cant get it right. All the different approches I have tried blink/flash every time my json updates and this is the closest I have managed to get.

Any help would be greatfull. I am taken back at how little examples there are of makers moving and updating without blinking…. and I really dont want to use google maps!

I tried to reset the makers = {}; but this did nothing.
Thank you


        data.BMS.forEach(function (obj) {
            if (obj.lat !== undefined && obj.lng !== undefined) {
                if (!markers.hasOwnProperty(obj.id)) {
                    markers[obj.id] = new L.Marker([obj.lat, obj.lng], {icon: panicNormal}).addTo(map) .bindTooltip(obj.name, 
                        {
                            permanent: true, 
                            direction: 'top',
                            offset: [0, 0]
                        });
                    markers[obj.id].previousLatLngs = [];
                    areaBounds.push([obj.lat, obj.lng]);
                    
                } else {
                    areaBounds.push([obj.lat, obj.lng]);
                    markers[obj.id].previousLatLngs.push(markers[obj.id].getLatLng());
                    if(obj.status == "TRUE"){
                        markers[obj.id].setIcon(panicAlarm);
                    }else{
                        if(obj.type == "MO"){
                            markers[obj.id].setIcon(panicNormal);
                        }else{
                            markers[obj.id].setIcon(lora);
                        }
                        
                    }
                    markers[obj.id].setLatLng([obj.lat, obj.lng]);
                }
                
            }else{
                //How do I remove the markers
            }
              
        });

>Solution :

You can use L.FeatureGroup() to add all markers to it and then remove all markers with .clearLayers()

var fg = L.featureGroup().addTo(map);
...
markers[obj.id] = new L.Marker([obj.lat, obj.lng], {icon: panicNormal}).addTo(fg) .bindTooltip
...
}else{
   //How do I remove the markers
   fg.clearLayers();
}

Leave a Reply