Clear all polylines from leaflet map

2020-07-06 02:41发布

问题:

I am struggling to clear all polylines from my map, i only clear the newest.

var polylines;

// add map polylines
function addPolyline(polyArray, colour) {
    polylines = L.polyline(polyArray, {color: colour});
    polylines.addTo(map);
}

// clear polylines   
function clearPolylines() {
    map.removeLayer(polylines);
}

where addPolylines is called multiple times and clear Polylines is called once. How can i clear all polylines on the map?

回答1:

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


回答2:

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)


回答3:

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