简体   繁体   中英

Leaflet clear geojson layer (polyline)

I am a creating a polyline using a geojson. The format of my geojson is as below:

var myLines = [{
    "type": "LineString",
    "coordinates": [[-75, 21.9], [-75.4, 22.7], [-76.5, 23.4]]
    }, {
    "type": "LineString",
     "coordinates": [[-105, 40], [-110, 45], [-115, 55]]
}];

        L.geoJson(myLines).addTo(map);

I have a clear polyline function as below:

function clear_polyline(){
$.each(myLines, function(ind,poly){
map.removeLayer(poly);
});
}

This function does not clear the layer nor does it throw any error. How do I clear a polyline in leaflet?

You need to remove the Leaflet layer from the map, not the GeoJSON object that the layer was created from. L.GeoJSON is a FeatureLayer that will contain all of the items in "myLines" so you should do something like this to remove it:

var linesFeatureLayer = L.geoJson(myLines);
linesFeatureLayer.addTo(map);

function clear_polyline() {
  map.removeLayer( linesFeatureLayer );
}
var linesFeatureLayer = L.geoJson(myLines);
linesFeatureLayer.clearlayer()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM