eventsvectoropenlayersopenlayers-8

Map loadstart event not firing with vector layers (openlayers)


I have a project in OpenLayers 8.2, where there are many types of layers in a map. As introduced in ol 6.14, I am using the 'loadstart' and 'loadend' events of the map object (https://openlayers.org/en/latest/examples/load-events.html).

import { Map, View } from 'ol'    
this.map = new Map({
    ...
});
this.map.on('loadstart', () => {
    console.warn("loadstart");
});

This fires flawlessly for most kinds of layers (TileWMS, ImageWMS, XYZ) but it doesn't work for vector layer. Vector layer is using VectorSource with custom loader function, which sends a request to the data service with each change of a current extent.

import sourceVector from 'ol/source/Vector'

let vectorSource = new sourceVector({
    loader: function (extent, resolution, projection) {
        let features = // fetch data using current extent
        this.addFeatures(features);
    }
});

I would expect, that when a loader function is called for the vector source, the 'loadstart' event would be triggered for the map object. Is that a potential bug or am I understanding it wrong? Or is there a manual way of letting the map know, that my vector layer is being loaded?


Solution

  • When using a custom loader, you need to handle two additional arguments to make loadend events work: a success and a failure callback:

    import sourceVector from 'ol/source/Vector'
    
    let vectorSource = new sourceVector({
        loader: function (extent, resolution, projection, success, failure) {
            try {
                let features = // fetch data using current extent
                this.addFeatures(features);
                success(features);
            } catch(e) {
                vectorSource.removeLoadedExtent(extent);
                failure();
            }
        }
    });
    

    Also see the API docs for the Vector source: https://openlayers.org/en/v8.1.0/apidoc/module-ol_source_Vector-VectorSource.html.