[GIS] How to render only those Leaflet layers which are in current map view

leafletweb-mapping

Is it possible to render Leaflet layers which are in current map view so that other layers which are not in that map view doesn't render? I have many polgons (buildings) and it is really slow rendering if they all renders so I thought it would be ok to divide buildings into many shapefiles which will render only in that map view.

Thanks.

Best Answer

Actually, splitting your shapefile in many others is not the right direction to go. Openlayers has introduced the BBoxStrategy which retrieve data when the map's viewport is changing.

It seems the leaflet vector layer plugin behaves the same way. So,be lazy, and let the JS library doing the job.

If you want to know a bit more on how it works, you will also find a manual implementation on the following page : https://groups.google.com/forum/#!msg/leaflet-js/1xT8aGNLS7c/CNhk4-BP6AoJ

map.on('moveend', function(e) {
   mylayer.clearLayers();
   if (map.hasLayer(mylayer) && map.getZoom() >= 16) {
      var bbox = map.getBounds().toBBoxString();
      $.getJSON("fetch-geojson.php?bbox="+bbox, function(data){
         mylayer.addData(data);
      });
   }
});