Leaflet – How to find existing markers, and delete markers?

you have to put your “var marker” out of the function. Then later you can access it :

var marker;
function onMapClick(e) {
        marker = new L.Marker(e.latlng, {draggable:true});
        map.addLayer(marker);
        marker.bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup();
};

then later :

map.removeLayer(marker)

But you can only have the latest marker that way, because each time, the var marker is erased by the latest. So one way to go is to create a global array of marker, and you add your marker in the global array.

Leave a Comment