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

JqueryLeaflet

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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 - Jquery

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 - Jquery

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 - Jquery

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 - Jquery

(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);
			}
		
	}
	
    }  

Solution 6 - Jquery

If you add the marker to the layer group, you can apply the removeLayer method to the layer group You need to define the marker variable outside of the function to be able to delete it

var marker;
function newMarker() {
 markerLayer = L.layerGroup();
 marker = new L.marker( [12, 13],
 {icon:greenMarker, clickable:true}).bindPopup("Hello Marker").addTo(markerLayer); 

markerLayer.removeLayer(marker);
};

Solution 7 - Jquery

When you save the reverence to the marker in the adding function the marker can remove it self. No need for arrays.

function addPump(){
   var pump = L.marker(cords,{icon: truckPump}).addTo(map).bindPopup($('<a href="#" class="speciallink">Remove ME</a>').click(function() {
		    map.removeLayer(pump);
		  })[0]);
		}

Solution 8 - Jquery

Have you tried layerGroup yet?

Docs here https://leafletjs.com/reference-1.2.0.html#layergroup

Just create a layer, add all marker to this layer, then you can find and destroy marker easily.

var markers = L.layerGroup()
const marker = L.marker([], {})
markers.addLayer(marker)

Solution 9 - Jquery

In my case, I have various layer groups so that users can show/hide clusters of like type markers. But, in any case you delete an individual marker by looping over your layer groups to find and delete it. While looping, search for a marker with a custom attribute, in my case a 'key', added when the marker was added to the layer group. Add your 'key' just like adding a title attribute. Later this is gotten an a layer option. When you find that match, you .removeLayer() and it gets rid of that particular marker. Hope that helps you out!

eventsLayerGroup.addLayer(L.marker([tag.latitude, tag.longitude],{title:tag.title, layer:tag.layer, timestamp:tag.timestamp, key:tag.key, bounceOnAdd: true, icon: L.AwesomeMarkers.icon({icon: 'vignette', markerColor: 'blue', prefix: '', iconColor: 'white'}) }).bindPopup(customPopup(tag),customOptions).on('click', markerClick)); 

function removeMarker(id){
    var layerGroupsArray = [eventsLayerGroup,landmarksLayerGroup,travelerLayerGroup,marketplaceLayerGroup,myLayerGroup];
    $.each(layerGroupsArray, function (key, value) {
        value.eachLayer(function (layer) {
            if(typeof value !== "undefined"){
                if (layer.options.layer){
                    console.log(layer.options.key);
                    console.log(id);
                    if (id === layer.options.key){
                        value.removeLayer(layer);
                    }
                }
            }
        });
    });
}

Solution 10 - Jquery

What I did to remove marker was this create a button who allow me do it

Hope i can help someone :)

//Button who active deleteBool
const button = document.getElementById('btn')

//Boolean who let me delete marker
let deleteBool = false

//Button function to enable boolean
button.addEventListener('click',()=>{
  deleteBool = true
})

// Function to delete marker 
const deleteMarker = (e) => {
    if (deleteBool) {
        e.target.removeFrom(map)
        deleteBooly = false
    }
}

//Initiate map
var map = L.map('map').setView([51.505, -0.09], 13);

//Create one marker
let marker = L.marker([51.5, -0.09]).addTo(map)
//Add Marker Function
marker.on('click', deleteMarker)

body {
  display: flex;
  flex-direction: column;
}

#map{
  width: 500px;
  height: 500px;
  margin: auto;
}

#btn{
  width: 50px;
  height: 50px;
  margin: 2em auto; 
}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
    <title>MovieCenter</title>
</head>

<body>
    <div id="map"></div>
    <button id="btn">Click me!</button>
    <script script="script" src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
    <script src="script.js"></script>
</body>

</html>

Solution 11 - Jquery

If you are using a L.Routing.control the answers that include saving the markers in an array will not work. They didn't work for me. I found that the L.Routing.control adds the markers automatically, and removing them is done by removing the L.Routing.control:

this.map.removeControl(this.routingControl)

The route was removed and all the waypoints/markers, except the first one, and when I console.logged the layers, the layer with waypoints was still there, idk why.

This solution finally worked for me:

this.map.eachLayer((layer: any) => {
  if (layer.options.waypoints && layer.options.waypoints.length) {
    this.map.removeLayer(layer);
   }
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjayView Question on Stackoverflow
Solution 1 - JqueryLaurent DebriconView Answer on Stackoverflow
Solution 2 - JqueryickeView Answer on Stackoverflow
Solution 3 - JqueryKedar.AitawdekarView Answer on Stackoverflow
Solution 4 - JqueryBrett DeWoodyView Answer on Stackoverflow
Solution 5 - Jquerydroid-zillaView Answer on Stackoverflow
Solution 6 - JqueryMahmoud MagdyView Answer on Stackoverflow
Solution 7 - JqueryF6FView Answer on Stackoverflow
Solution 8 - JquerySon Tr.View Answer on Stackoverflow
Solution 9 - JqueryRonnie RoystonView Answer on Stackoverflow
Solution 10 - JqueryRaul Brito GonzalezView Answer on Stackoverflow
Solution 11 - JquerychriszichriszView Answer on Stackoverflow