[GIS] Using layer loadstart & loadend events in OpenLayers 3

eventslayersloadingopenlayers

OpenLayers 2 has these layer events "loadstart & loadend."

What is equivalent to them in OpenLayers 3?

While a vector layer loads and is rendered, I need to show a loading icon.

Best Answer

Assuming you use an ol.layer.Vector with an ol.source.GeoJSON you can use something like this:

var vectorSource = new ol.source.GeoJSON({
  projection : 'EPSG:3857',
  url: 'http://examples.org/fearures.json'
});

var vectorLayer = new ol.layer.Vector({
  source: vectorSource
});

map.addLayer(vectorLayer);

// show loading icon
// ...

var listenerKey = vectorSource.on('change', function(e) {
  if (vectorSource.getState() == 'ready') {
    // hide loading icon
    // ...
    // and unregister the "change" listener 
    ol.Observable.unByKey(listenerKey);
    // or vectorSource.unByKey(listenerKey) if
    // you don't use the current master branch
    // of ol3
  }
});

This shows how to get a notification when the vector source is loaded. It only works with sources inheriting from ol.source.StaticVector. Examples include ol.source.GeoJSON and ol.source.KML .

Also, note that this code may no longer work in the future when ol3 will provide a consistent way to know if/when a source is loaded.