Joel James
Joel James

Reputation: 3938

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?

Upvotes: 3

Views: 15705

Answers (2)

Small Jheng
Small Jheng

Reputation: 19

var linesFeatureLayer = L.geoJson(myLines);
linesFeatureLayer.clearLayers()

Upvotes: 1

InPursuit
InPursuit

Reputation: 3293

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

Upvotes: 13

Related Questions