Question

I am trying to dynamically load and remove large geojson files (>5MB) as geojson overlays using L.control.layers(baselayers, overlays).addTo(map) function. Loading the geojson files is fine when the layer is selected in the control, and the layer disappears when you de-select the layer in the overlay control. The problem is that if you re-select the layer, the geojson file appears to be overlayed twice, like the browser cached the first file and is loading and overlaying both files on top of the map. The files are quite large and by the third time you select and de-select the layer, the load time is quite long, and presumably will crash the browser at some point. Does anyone have any thoughts about what I am doing wrong or how I can clear the browser cache when the layer is de-selected in the overlay control?

The relevant code is as follows:

var medAgeLayer = L.geoJson();
var popLayer = L.geoJson(null, {
                weight:0,onEachFeature:onEachFeature});
var overlays = {"median age":medAgeLayer, "Population":popLayer};
L.control.layers(baselayers, overlays).addTo(map);

map.on('overlayadd', function(eventLayer){
    if(eventLayer.name === "median age"){
    $.getJSON("http://localhost/flare7.json", function(data){
            medAgeLayer.addData(data).addTo(map);
            });
        }
    else if(eventLayer.name === "Population"){
$.getJSON("./flare5.json", function(json){
        popLayer.addData(json).addTo(map)
        });
      };
    });

map.on('overlayremove', function(eventLayer){
    map.removeLayer(eventLayer.layer);
    });
Was it helpful?

Solution

I found the solution to the problem. I needed to call .clearLayers() before calling the .addData() method on the geojson variables, like so:

map.on('overlayadd', function(eventLayer){
if(eventLayer.name === "median age"){
$.getJSON("http://localhost/flare7.json", function(data){
        medAgeLayer.clearLayers();
        medAgeLayer.addData(data);
        });
    }
else if(eventLayer.name === "Population"){
$.getJSON("./flare5.json", function(json){
    popLayer.clearLayers();
    popLayer.addData(json).addTo(map)
    });
  };
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top