1
votes

the following code will enable the creation of polygon on the the map .This works fine but previous geojson layer is also visible when new layer is added.

$http.get("./json/sf.geo.json").success(function(data, status) {
    leafletData.getMap('lfdt').then(function(map){    
    var polyLayer = L.geoJson(data, {filter: layerFilter}).addTo(map);
    function clear_polygon() {
        map.removeLayer( polyLayer );
            }

   function layerFilter(feature) {
          if (feature.properties.zip === $scope.code) return true;
        }
        map.fitBounds(polyLayer.getBounds(), {
        padding: [40, 40]
    });
});

I am having dropdown of zipcodes and i want to show selected zipcode boundaries on leaflet map. the problem is when user is selected another zipcode, new polygon is showing but the old one is also showing as you can see in the below image.

enter image description here

Can Anyone please help me where should i write removeLayers(). Please suggest me.

1

1 Answers

2
votes

The problem is that by using var to re-declare your variable, the reference to the previous object is lost.

That means, first, you have to declare your variable outside of the get call. just in top of your javascript file.

var polyLayer;

then just remove the var from that line in the get function. change

var polyLayer = L.geoJson(data, {filter: layerFilter}).addTo(map);

to

if(polyLayer)
{
    map.removeLayer(polyLayer); // remove the old polygon...
}
polyLayer = L.geoJson(data, {filter: layerFilter}).addTo(map); // ...then add the new polygon