Clear all polylines from leaflet map
You'll have to remember them all or cheat a bit and peek into map._layers
to find them.
EDIT adding sample code by @Ben:
function clearMap() {
for(i in m._layers) {
if(m._layers[i]._path != undefined) {
try {
m.removeLayer(m._layers[i]);
}
catch(e) {
console.log("problem with " + e + m._layers[i]);
}
}
}
}
The following will remove both polygons and markers but keep the image tiles in the background:
for (i in map._layers) {
if (map._layers[i].options.format == undefined) {
try {
map.removeLayer(map._layers[i]);
} catch (e) {
console.log("problem with " + e + map._layers[i]);
}
}
}
You can add the polyline to a layerGroup and easily add/remove it to/from the map. Something like this:
pLineGroup = L.layerGroup()
var latlngs = [
[45.51, -122.68],
[37.77, -122.43],
[34.04, -118.2]
];
this.pLineGroup.addLayer(L.polyline(latlngs, {color: 'red'}))
pLineGroup.addTo(map)
pLineGroup.removeFrom(map)
You can create an array to store all polylines present in the map.
var polylines = [];
When create each polyline we add it to our array:
var polyline = new L.Polyline(latlongs, {
color: 'red',
opacity: 1,
weight: 1,
clickable: false
}).addTo(map);
polylines.push(polyline);
And now, when ever we need to clear our polylines from the map we can do:
polylines.forEach(function (item) {
map.removeLayer(item)
});