Limiting the amount of vector features displayed is important in OpenLayers, but this can lead to some features not being displayed. When moving or zooming in, it's necessary to "refresh" the features with an XHR call. In OpenLayers 2, this could be achieved by calling
bboxstrategy.update({ force: true })
on a map's 'zoomend' event.
In OL2 with the SVG renderer, the repaint was very smooth, hardly noticeable.
In OL3, it appears necessary to call:
vector.getSource().clear();
on a map's 'moveend' event.
This results in an annoying flash when OL3 renders the new features.
Does anyone know of a better technique to reload features but avoid the flash?
Here is a working flashy example, adapted from here
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WFS</title>
<link rel="stylesheet" href="https://openlayers.org/en/v4.6.4/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.6.4/build/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script>
function onMoveEnd( evt ) {
vector.getSource().clear();
}
var vectorSource = new ol.source.Vector({
format: new ol.format.GeoJSON(),
url: function(extent) {
return 'https://ahocevar.com/geoserver/wfs?service=WFS&' +
'version=1.1.0&request=GetFeature&typename=osm:water_areas&' +
'maxFeatures=500&outputFormat=application/json&srsname=EPSG:3857&' +
'bbox=' + extent.join(',') + ',EPSG:3857';
},
strategy: ol.loadingstrategy.bbox
});
var vector = new ol.layer.Vector({
source: vectorSource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 255, 1.0)',
width: 2
})
})
});
var raster = new ol.layer.Tile({
source: new ol.source.OSM({
})
});
var map = new ol.Map({
layers: [raster, vector],
target: document.getElementById('map'),
view: new ol.View({
center: [-8908887.277395891, 5381918.072437216],
maxZoom: 19,
zoom: 12
})
});
map.on('moveend', onMoveEnd);
</script>
</body>
</html>