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

jay picture jay · Mar 28, 2012 · Viewed 162.4k times · Source

I have started using leaflet as an open source map, http://leaflet.cloudmade.com/

The following jQuery code will enable the creation of markers on the map on map click:

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

But there is currently no way for me (in my code) to delete existing markers, or find all the markers i've created on a map and put them into an array. Can anyone help me understand how to do this? Leaflet documentation is available here : http://leaflet.cloudmade.com/reference.html

Answer

Laurent Debricon picture Laurent Debricon · Apr 5, 2012

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.