Leaflet clear geojson layer (polyline)

13,549

Solution 1

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

Solution 2

var linesFeatureLayer = L.geoJson(myLines);
linesFeatureLayer.clearlayer()
Share:
13,549
Joel James
Author by

Joel James

Updated on June 14, 2022

Comments

  • Joel James
    Joel James almost 2 years

    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?

  • Manfred Wuits
    Manfred Wuits over 7 years
    i think it should rather read: linesFeatureLayer.clearLayers()
  • Majid Hojati
    Majid Hojati almost 2 years
    clearLayers is not a function this method does not work on L.geoJSON