Loading GeoJSON layers from Geoserver to Leaflet Map based on the current bounding box

mblais29 picture mblais29 · Aug 7, 2014 · Viewed 16.5k times · Source

Currently, I have over 25000 points for my map. When I load all the points the map is extremely slow. Therefore, I want to load the data only at a certain zoom level and bounding box(users view). How can I accomplish that with my current code?

var map = new L.Map('map', {center: new L.LatLng(54.0000, -125.0000), zoom: 5});
  var googleLayer = new L.Google('ROADMAP');      
  map.addLayer(googleLayer);

function BoundingBox(){
var bounds = map.getBounds().getSouthWest().lng + "," +     map.getBounds().getSouthWest().lat + "," + map.getBounds().getNorthEast().lng + "," + map.getBounds().getNorthEast().lat;
return bounds;
}
var geoJsonUrl ="http://localhost:8080/geoserver/Wells/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=Wells:bc_well_data_wgs&maxFeatures=25&outputFormat=text/javascript&format_options=callback:loadGeoJson"; 

var geojsonLayerWells = new L.GeoJSON();

function loadGeoJson(data) {
console.log(data);
geojsonLayerWells.addData(data);
};

$.ajax({ 
    url: geoJsonUrl, 
    dataType : 'jsonp',
    success: loadGeoJson
    });


map.on('moveend', function(){

    if(map.getZoom() >= 18){

        map.removeLayer(geojsonLayerWells);

        }
    if(map.getZoom() < 18){
        map.addLayer(geojsonLayerWells);
        }
        console.log(map.getZoom());
        console.log(BoundingBox());
    });

Answer

mblais29 picture mblais29 · Aug 14, 2014

Here is how I solved it, changed everything around.

var wellmaxzoom = 11;       
var geojsonLayerWells = new L.GeoJSON();

function loadGeoJson(data) {
    console.log(data);
    geojsonLayerWells.addData(data);
    map.addLayer(geojsonLayerWells);
};

map.on('moveend', function(){
 if(map.getZoom() > wellmaxzoom){
    var geoJsonUrl ='http://localhost:8080/geoserver/cite/ows'; 
    var defaultParameters = {
        service: 'WFS',
        version: '1.0.0',
        request: 'getFeature',
        typeName: 'cite:bc_well_data_wgs',
        maxFeatures: 3000,
        outputFormat: 'application/json'
        };

    var customParams = {
        bbox: map.getBounds().toBBoxString(),
        };
    var parameters = L.Util.extend(defaultParameters, customParams);
    console.log(geoJsonUrl + L.Util.getParamString(parameters));

    $.ajax({
        url: geoJsonUrl + L.Util.getParamString(parameters),
        datatype: 'json',
        jsonCallback: 'getJson',
        success: loadGeoJson
        });
    }else{
    map.removeLayer(geojsonLayerWells);
    };
});