multigoodverse
multigoodverse

Reputation: 8072

How to set a minimum zoom for loading a JSON layer?

I was able to come up with this Leaflet web map.

I generated the HTML and the JS files using a QGIS tool called qgis2web that gets as input layers of a QGIS project and produces the web files.

However, when one of my layers has 50,000+ points, Javascript crashes and the navigation gets very slow. I heard I could implement a conditional that would only load a layer when the user had zoomed to a certain point. I know I need to write something like:

 if (map.getZoom() > 8 {  
 "layer loading code goes here"
}

But I don't know what to put inside the conditional as I am not sure where the loading of a layer occurs. Let's suppose I want to load the Sells LoJack points when the user has reached a zooming factor of 8. Anyone knows how that would be implemented?

Upvotes: 0

Views: 244

Answers (1)

ghybs
ghybs

Reputation: 53205

A layer with hundreds to thousands of points will certainly make your browser having a hard time / freeze / crash as you have experienced.

You should be interested in clustering and/or canvas Leaflet plugins.

If you want to stick with the technique to show your layer only above a given zoom level, you would probably have to do something like:

map.on("zoomend", function () {
  if (map.getZoom() >= 8) {
    map.addLayer(myCrowdedLayer);
  } else {
    map.removeLayer(myCrowdedLayer);
  }
});

Refer to Leaflet documentation for adding and removing layers to map.

Of course you would have to match what qgis2web uses for map of myCrowdedLayer.

Note: even with this technique, there is a high chance your browser still has a hard time / crashes. I really recommend using clustering plugins. See Leaflet.markercluster for example.

Upvotes: 1

Related Questions