从传单地图中清除所有折线

Vin*_*owe 9 javascript leaflet

我正在努力清除地图上的所有折线,我只清楚最新的.

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);
}
Run Code Online (Sandbox Code Playgroud)

其中addPolylines被多次调用,而clear Polylines被调用一次.如何清除地图上的所有折线?

flu*_*lup 23

你必须记住它们或者作弊并偷看map._layers才能找到它们.

编辑@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]);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我不确定这是否是_good_方式,但我使用[this function](https://gist.github.com/anonymous/5417531):`function clearMap(){for(i in m. _layers){if(m._layers [i] ._ path!= undefined){try {m.removeLayer(m._layers [i]); } catch(e){console.log("问题与"+ e + m._layers [i]); }.} (5认同)
  • 图层可以只用于线条而不是将它们直接添加到地图中吗?然后删除图层就可以了。 (2认同)

M.R*_*eza 6

您可以将折线添加到图层组中,并轻松地将其添加到地图中或从地图中删除。像这样的东西:

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)
Run Code Online (Sandbox Code Playgroud)