OpenLayers 3 catch tiles loaded event
Asked Answered
G

2

5

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(){  });
Gigigigli answered 13/10, 2014 at 19:18 Comment(3)
It is a very good question. I just spent some time grepping the source code and the is an opt_tileCallback method in renderer/layerrenderer.js, but I can't see how to attach to this in the first place, and don't have time to investigate further.Stasiastasis
Same question. Anyone knows this?Sikes
Status update from the developers of ol: github.com/openlayers/ol3/issues/2832Gigigigli
N
6

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.

Nauru answered 20/5, 2015 at 22:34 Comment(0)
W
1

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

Winnow answered 3/4, 2015 at 22:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.