1

I am trying to delete all the markers on my map, but code below only the last added marker will be deleted.

Is there a way to get a new a instance of map i mean on click of a button is there a way to reinitialize the map in leaflet?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://npmcdn.com/leaflet@1.0.0-rc.3/dist/leaflet.css" />
</head>
<body>
<script src="https://npmcdn.com/leaflet@1.0.0-rc.3/dist/leaflet.js"></script>
<script src="../leaflet/lib/AnimatedMarker.js"></script>

<style>
    #mapid { height: 500px; }
</style>

<div id="mapid"></div>
<script>
    var mymap = L.map('mapid').setView([40.68510, -73.94136], 13);
    L.tileLayer('http://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png', {
        attribution: '&copy; Openstreetmap France | &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
    }).addTo(mymap);

    var marker = L.marker([40.68510, -73.94136]).addTo(mymap);
    var marker = L.marker([40.68576, -73.94149]).addTo(mymap);
    var marker = L.marker([40.68649, -73.94165]).addTo(mymap);



    mymap.removeLayer(marker);
</script>

</body>
</html>
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
dhana lakshmi
  • 847
  • 1
  • 12
  • 29
  • Give each `marker` a different variable name, e.g. `marker1` `marker2`... you should then be able to delete each: `mymap.removeLayer(marker2)` – Pekka Oct 01 '16 at 08:11
  • I edited the first paragraph. The second I don’t understand so I left it - can you clarify what that is about? It seems unrelated to your question? – Pekka Oct 01 '16 at 08:12
  • As a tip, remember to capitalize your I’s in „I am“ etc.! – Pekka Oct 01 '16 at 08:13
  • it there are 100 markers there will be 100s variable then please say how to deal with it – dhana lakshmi Oct 01 '16 at 09:08
  • In the second paragraph i mean is there as way to reinitialize the map container – dhana lakshmi Oct 01 '16 at 09:10
  • 1
    In that case, you’d want to use an array. Each marker would then be an array element. Here is an example http://stackoverflow.com/questions/17371039/how-to-add-markers-bulk-in-leaflet – Pekka Oct 01 '16 at 09:10
  • If you have 100s of markers, you may want to look into clustering later https://github.com/Leaflet/Leaflet.markercluster – Pekka Oct 01 '16 at 09:11
  • Re your second paragraph, is that an unrelated question? It’s confusing, if it’s a separate question it might need to be put separately – Pekka Oct 01 '16 at 09:12

1 Answers1

4

Instead of adding markers to the map, add your markers to a layerGroup and add the layerGroup to the map. You can remove the markers using clearLayers() method.

var markers = L.layerGroup([marker1, marker2]).addTo(map);
markers.clearLayers();
YaFred
  • 9,698
  • 3
  • 28
  • 40