WeSt
WeSt

Reputation: 2684

Leaflet - Event on tiles loading

I am currently developing a map-based application and need a way to get notified when Leaflet is pulling tiles from the TileProvider (which, in my case, is MapBox). I read the Leaflet documentation, especially the part with the TileLayer. Currently, I am using the following code to attach a tileload handler:

map.eachLayer(function (layer) {
    layer.on('tileload', function(e) {
        console.log(e);
    });
});

Is there a better way to get the TileLayer of the current map? One problem with this approach is that I hook the handler to all layers (although only TileLayers will raise events, it is unclean to hook it too all layers). Or can I attach the handler directly to the map instance somehow?

Update

I initialize the map with the following MapBox code snippet:

map = L.mapbox.map( element, '...', mapOptions );

This automatically creates a TileLayer (and several other layers), attaches them to the map object and returns this object for later use.

Upvotes: 5

Views: 4748

Answers (2)

iH8
iH8

Reputation: 28628

If you've got a lot of L.mapbox.TileLayer instances and you don't want to add the eventhandler manually to each instance like Alexandru Pufan suggests in his answer you could still use a loop and Object's instanceof method:

map.eachLayer(function (layer) {
    if (layer instanceof L.mapbox.TileLayer) {
        layer.on('tileload', function(e) {
            console.log(e);
        });
    }
});

After reading your comment on Alexandru's answer i'm guessing you only have one layer, then it would be best to add it manually to the instance, which is possible with L.mapbox.TileLayer like this:

var layer = L.mapbox.tileLayer(YOUR MAP ID);
layer.on('tileload', function(e) {
    console.log(e);
});

var map = L.mapbox.map('mapbox', null, {
    'center': [0, 0],
    'zoom': 0,
    'layers': [layer]
});

Upvotes: 3

Alexandru Pufan
Alexandru Pufan

Reputation: 1912

Why not use tileload event directly on the tile layer, like this:

//create a variable to store the tilelayer
var osm = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

//add the tileload event directly to that variable
osm.on('tileload', function (e) {
    console.log(e);
});

Upvotes: 8

Related Questions