Clear all polylines from leaflet map

烂漫一生 提交于 2020-01-01 08:35:58

问题


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:


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


来源:https://stackoverflow.com/questions/14585688/clear-all-polylines-from-leaflet-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!