Fabio Marzocca
Fabio Marzocca

Reputation: 1677

How to set a timeout to tileerror on L.tileLayer?

I am getting layers from a WMS service, but sometimes it happens that the connection to the server times out. In those cases, the application hangs for a long time waiting for a NET_ERR, but the timeout is too long.

I am catching the error with "tileerror":

myLayer.on('tileerror', function(error, tile) {
    console.log(error);
    console.log(tile);
    switchToBackupServer();
    });

How can I shorten the default timeout and take the corrective action?

Upvotes: 4

Views: 952

Answers (1)

IvanSanchez
IvanSanchez

Reputation: 19089

How can I shorten the default timeout and take the corrective action?

You can't. It's browser-specific, and it doesn't have an API.

You can, however, create your own subclass of L.TileLayer and add some extra logic. See these lines in the default implementation of L.TileLayer.prototype.createTile:

    DomEvent.on(tile, 'load', Util.bind(this._tileOnLoad, this, done, tile));
    DomEvent.on(tile, 'error', Util.bind(this._tileOnError, this, done, tile));

You could trigger a shorter timeout with something like:

    var loadCallback = Util.bind(this._tileOnLoad, this, done, tile);
    var errorCallback = Util.bind(this._tileOnError, this, done, tile);

    DomEvent.on(tile, 'load', loadCallback);
    DomEvent.on(tile, 'error', errorCallback);

    setTimeout(function(){
        // Do nothing if the tile has already been loaded successfully
        if (tile.loaded) return;

        // Prevent any further events from triggering
        DomEvent.off(tile, 'load', loadCallback);
        DomEvent.off(tile, 'error', errorCallback);

        // Trigger the error
        errorCallback();
    });

There are probably some race conditions that I cannot foresee right now, but that's the general idea.

Upvotes: 2

Related Questions