Reputation: 947
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/[email protected]/dist/leaflet.css" />
</head>
<body>
<script src="https://npmcdn.com/[email protected]/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: '© Openstreetmap France | © <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>
Upvotes: 1
Views: 6008
Reputation: 10008
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();
Upvotes: 4