0

We have a web application that displays a map with lots of point and polygon features. The features are loaded as WKT from our web API along with other data.

Currently we just fetch all the features when the web first loads, but naturally this leads to a lot of unnecessary data being transferred. The polygon geometries in particular take a lot of bandwidth, and most of them will never be displayed to the user since the polygon layer is only visible when zoomed in.

Is there a way to have OL automatically make API queries for only the necessary extent?

Ideally we'd like OL to make an API query for the current extent and visible layers and merge the resulting data to the already loaded features.

We use OL 5.

1

You have an illustration in the doc (reproduced below)

The important part is the strategy strategy: ol.loadingstrategy.bbox. It purpose is to make the source load data each time you change the bbox by zooming or panning. I've added some comments inline in the code for your particular case.

var vectorSource = new ol.source.Vector({
  format: new ol.format.GeoJSON(), // Replace with new ol.format.WKT(),
  loader: function(extent, resolution, projection) {
     var proj = projection.getCode();
     // Change URL to your server, you may need to reproject
     // extent to lon, lat with
     // ol.extent.applyTransform(extent, ol.proj.getTransform(projection, "EPSG:4326"));
     var url = 'https://ahocevar.com/geoserver/wfs?service=WFS&' +
         'version=1.1.0&request=GetFeature&typename=osm:water_areas&' +
         'outputFormat=application/json&srsname=' + proj + '&' +
         'bbox=' + extent.join(',') + ',' + proj;
     var xhr = new XMLHttpRequest();
     xhr.open('GET', url);
     var onError = function() {
       vectorSource.removeLoadedExtent(extent);
     }
     xhr.onerror = onError;
     xhr.onload = function() {
       if (xhr.status == 200) {
         vectorSource.addFeatures(
             vectorSource.getFormat().readFeatures(xhr.responseText));
       } else {
         onError();
       }
     }
     xhr.send();
   },
   strategy: ol.loadingstrategy.bbox
 });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.