Leaflet - How to find existing markers, and delete markers?
Solution 1
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.
Solution 2
You can also push markers into an array. See code example, this works for me:
/*create array:*/
var marker = new Array();
/*Some Coordinates (here simulating somehow json string)*/
var items = [{"lat":"51.000","lon":"13.000"},{"lat":"52.000","lon":"13.010"},{"lat":"52.000","lon":"13.020"}];
/*pushing items into array each by each and then add markers*/
function itemWrap() {
for(i=0;i<items.length;i++){
var LamMarker = new L.marker([items[i].lat, items[i].lon]);
marker.push(LamMarker);
map.addLayer(marker[i]);
}
}
/*Going through these marker-items again removing them*/
function markerDelAgain() {
for(i=0;i<marker.length;i++) {
map.removeLayer(marker[i]);
}
}
Solution 3
Here is the code and demo for Adding the marker, deleting any of the marker and also getting all the present/added markers :
Here is the entire JSFiddle code . Also here is the full page demo.
Adding the marker :
// Script for adding marker on map click
map.on('click', onMapClick);
function onMapClick(e) {
var geojsonFeature = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [e.latlng.lat, e.latlng.lng]
}
}
var marker;
L.geoJson(geojsonFeature, {
pointToLayer: function(feature, latlng){
marker = L.marker(e.latlng, {
title: "Resource Location",
alt: "Resource Location",
riseOnHover: true,
draggable: true,
}).bindPopup("<input type='button' value='Delete this marker' class='marker-delete-button'/>");
marker.on("popupopen", onPopupOpen);
return marker;
}
}).addTo(map);
}
Deleting the Marker :
// Function to handle delete as well as other events on marker popup open
function onPopupOpen() {
var tempMarker = this;
// To remove marker on click of delete button in the popup of marker
$(".marker-delete-button:visible").click(function () {
map.removeLayer(tempMarker);
});
}
Getting all the markers in the map :
// getting all the markers at once
function getAllMarkers() {
var allMarkersObjArray = []; // for marker objects
var allMarkersGeoJsonArray = []; // for readable geoJson markers
$.each(map._layers, function (ml) {
if (map._layers[ml].feature) {
allMarkersObjArray.push(this)
allMarkersGeoJsonArray.push(JSON.stringify(this.toGeoJSON()))
}
})
console.log(allMarkersObjArray);
}
// any html element such as button, div to call the function()
$(".get-markers").on("click", getAllMarkers);
Solution 4
Here's a jsFiddle that lets you to create markers using your onMapClick
method, then delete them by clicking a link.
The process is similar to undefined's - add each new marker to a markers
array so you can access a specific marker when you want to interact with it later.
Solution 5
(1) add layer group and array to hold layers and reference to layers as global variables:
var search_group = new L.LayerGroup(); var clickArr = new Array();
(2) add map
(3) Add group layer to map
map.addLayer(search_group);
(4) the add to map function, with a popup that contains a link, which when clicked will have a remove option. This link will have, as its id the lat long of the point. This id will then be compared to when you click on one of your created markers and you want to delete it.
map.on('click', function(e) {
var clickPositionMarker = L.marker([e.latlng.lat,e.latlng.lng],{icon: idMarker});
clickArr.push(clickPositionMarker);
mapLat = e.latlng.lat;
mapLon = e.latlng.lng;
clickPositionMarker.addTo(search_group).bindPopup("<a name='removeClickM' id="+e.latlng.lat+"_"+e.latlng.lng+">Remove Me</a>")
.openPopup();
/* clickPositionMarker.on('click', function(e) {
markerDelAgain();
}); */
});
(5) The remove function, compare the marker lat long to the id fired in the remove:
$(document).on("click","a[name='removeClickM']", function (e) {
// Stop form from submitting normally
e.preventDefault();
for(i=0;i<clickArr.length;i++) {
if(search_group.hasLayer(clickArr[i]))
{
if(clickArr[i]._latlng.lat+"_"+clickArr[i]._latlng.lng==$(this).attr('id'))
{
hideLayer(search_group,clickArr[i]);
clickArr.splice(clickArr.indexOf(clickArr[i]), 1);
}
}
}
Related videos on Youtube

jay
I’m software engineer / software consultant with 11 years experience working with teams in Shanghai, New York, and London. Read more about me at: http://joshuaballoch.github.io/about
Updated on May 31, 2021Comments
-
jay over 1 year
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
-
neogeomat over 8 yearsThe best way is to create a layergroup. Then we can add markers to layergroup. Layergroup allows to control all markers at once.
-
Zar Shardan about 8 yearsLayer Groups is definitely the cleanest way to handle this. Docs here: leafletjs.com/reference.html#layergroup
-
Harijs Krūtainis about 1 yearmarker.remove();
-
-
jackyalcine over 10 yearsShould be a way to collect all of the layers used by Leaflet. :/
-
flup almost 10 yearsThe layers are internally stored in
map._layers
. -
Michael Wales over 9 years@jackyalcine: Look at LayerGroup and FeatureGroup
-
Miguel Stevens over 8 yearsNice! Only one question, The markers() array still keeps the deleted ones, How would you delete the markers also from the array? Thanks!
-
Brett DeWoody over 8 yearsYou could use
delete
to remove the item. For exampledelete markers[$(this).attr('id')];
. -
FoamyGuy over 8 yearsThe cloudmade API that is included for the tiles in this example seems to be inactive now. Here is a fork that is the exact same, but uses mapquest tile server instead of cloudmade, so no API key needed. jsfiddle.net/nqDKU
-
Samuel Méndez over 5 yearsFor getting all markers,
map._layers[ml].feature
doesn't work anymore.