coure2011
coure2011

Reputation: 42404

Getting the bounds of loaded tile of leaflet

Using leaflet is there any way I can get the bounds (NorthEast, SouthWest) of a loaded tile? I want to request the server to load the markers only for a particular tile which is loaded, so that when user is panning/dragging the map he can easily see the new markers on new area.

Upvotes: 3

Views: 1851

Answers (1)

IvanSanchez
IvanSanchez

Reputation: 19049

What you really want to do is a subclass of L.GridLayer. This will allow fine control over loaded/unloaded tiles, and is the best way to use the private L.GridLayer._tileCoordsToBounds() method.

With some basic handling of loaded markers, it should look like:

L.GridLayer.MarkerLoader = L.GridLayer.extend({

    onAdd: function(map){
        // Add a LayerGroup to the map, to hold the markers
        this._markerGroup = L.layerGroup().addTo(map);
        L.GridLayer.prototype.onAdd.call(this, map);

        // Create a tilekey index of markers
        this._markerIndex = {};
    },

    onRemove: function(map){
        this._markergroup.removeFrom(map);
        L.GridLayer.prototype.onRemove.call(this, map);
    };

    createTile: function(coords, done) {

        var tileBounds = this._tileCoordsToBounds(coords);
        var tileKey = this._tileCoordsToKey(coords);

        var url = ...;  // Compute right url using tileBounds & coords.z

        fetch(url).then(function(res){
            if (!key in this._markerIndex) { this._markerIndex[key] = []; }

            // unpack marker data from result, instantiate markers
            // Loop as appropiate
            this._markerGroup.addLayer(marker);
            this._markerIndex[key] = marker;

            done(); // Signal that the tile has been loaded successfully
        });
    },

    _removeTile: function (key) {
        for (var i in this._markerIndex[key]) {
            this._markerGroup.remove(this._markerIndex[key][i]);
        }

        L.GridLayer.prototype._removeTile.call(this, key);
    }
});

Please note that zooming might be a source of bugs and graphical glitches (markers being removed because a tile unloads, before the markers at the new zoom level are loaded). Beware of that.

Upvotes: 4

Related Questions