How can I catch the tiles loaded event in OpenLayers 3? In OpenLayers 2 this could be done by catching the "loadend" event from the baselayer of the map:
map.baseLayer.events.register('loadend' , false, function(){ });
tileloadstart
, tileloadend
, and tileloaderror
events can be subscribed to on tile sources since OpenLayers v3.3.
You can use something similar to the following:
var tilesLoading = 0,
tilesLoaded = 0;
tileLayer.getSource().on('tileloadend', function () {
tilesLoaded++;
if (tilesLoading === tilesLoaded) {
console.log(tilesLoaded + ' tiles finished loading');
tilesLoading = 0;
tilesLoaded = 0;
//trigger another event, do something etc...
}
});
tileLayer.getSource().on('tileloadstart', function () {
this.tilesLoading++;
});
EDIT: I used to use this technique to help determine when the map finished loading. Since this answer was written, OpenLayers added a rendercomplete
event which make things a lot simpler: https://openlayers.org/en/latest/apidoc/module-ol_render_Event-RenderEvent.html.
You can hook this up in the following way as of now, until something is added into the core.
tileSource.setTileLoadFunction(( function(){
var numLoadingTiles = 0;
var tileLoadFn = tileSource.getTileLoadFunction();
return (tile, src) => {
console.log(src);
if (numLoadingTiles === 0) {
console.log('loading');
}
++numLoadingTiles;
var image = tile.getImage();
image.onload = image.onerror = function(){
--numLoadingTiles;
if (numLoadingTiles === 0) {
console.log('idle');
}
};
tileLoadFn(tile, src);
};
})());
You can see all the tile source classes that this can be used for here: http://openlayers.org/en/v3.4.0/apidoc/ol.source.TileImage.html?unstable=true#setTileLoadFunction
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With