Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

leaflet

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

like image 845
jay Avatar asked Mar 28 '12 16:03

jay


People also ask

How do you delete a marker in leaflet?

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.

How do you show markers in leaflet?

Adding a Simple Marker Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional). Step 2 − Create a Layer object by passing the URL of the desired tile. Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

How many markers can leaflet handle?

The Clusterer can handle 10,000 or even 50,000 markers (in chrome).

How do you refresh a leaflet map?

To refresh leaflet map when map container is already initialized with JavaScript, we call the off and remove methods before reloading the map. map. off(); map. remove();


1 Answers

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.

like image 129
Laurent Debricon Avatar answered Sep 23 '22 10:09

Laurent Debricon