Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenLayers 3 catch tiles loaded event

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(){  });
like image 345
klickagent.ch Avatar asked Oct 13 '14 19:10

klickagent.ch


2 Answers

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.

like image 157
John Galambos Avatar answered Oct 26 '22 08:10

John Galambos


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

like image 1
Poul K. Sørensen Avatar answered Oct 26 '22 07:10

Poul K. Sørensen