OpenLayers – How to Refresh Vector Source with BBOX Strategy After Map Moved

bboxjavascriptopenlayersvector-layer

I have a vector layer, in GeoJSON with a Vector source on which I applied the BBOX strategy. I have unique IDs for each feature in the layer and having a look at the network tab in the browser the strategy is working, bringing back all the features at a given extent, whenever I move the map.

The problem is that the returned features sum up on the Vector source and they don't get replaced by the new ones in the extent (those which are not in the extent just stay in the source).

How could I refresh the source with the new returned features (only in the current extent) and removing from the source those which are not in the extent?

What I am trying to achieve is a way to get the features loaded with each map moved, clear the vector source and replace the features with the new loaded. But I am not sure how and where to accomplish this.

    var vectorSource = new ol.source.Vector({
    format: formatGEOJSON,
    url: function(extent) {
        return 'http://localhost/geoserver/wfs?service=WFS&' +
        'version=1.1.0&request=GetFeature&typename=workspace:layer&' + 
        'outputFormat=application/json&srsname=EPSG:27700&bbox='.concat(extent.join(','), ',EPSG:27700');
    },
    strategy: ol.loadingstrategy.bbox
});
var vectorLayer = new ol.layer.Vector({
    source: vectorSource,
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: 'rgba(0, 204, 0, 1)',
            width: 2
        }),
        fill: new ol.style.Fill({
            color: 'rgba(0, 204, 0, 0.2)'
            }
        )
    }),
    minResolution: 0,
    maxResolution: 20,

});

Best Answer

Building on @TomazicM 's suggestion (which results in another infinite loop) a refinement is needed to check if the bbox has changed before clearing the source:

var vectorSource = new ol.source.Vector({
    format: formatGEOJSON,
    url: function(extent) {
        return 'http://localhost/geoserver/wfs?service=WFS&' +
        'version=1.1.0&request=GetFeature&typename=workspace:layer&' + 
        'outputFormat=application/json&srsname=EPSG:27700&bbox='.concat(extent.join(','), ',EPSG:27700');
    },
    strategy: function(extent) {  
        var bbox = extent.join(',');
        if (bbox != this.get('bbox')) {
            this.set('bbox', bbox);
            vectorSource.clear();
        }
        return [extent];
    }
});