warmspringwinds
warmspringwinds

Reputation: 1177

How to get coords of tiles that are currently visible?

I need to get x/y (where x and y are coords that leaflet.js uses to query corresponding url with x/y/z for tiles) coords of currently visible tiles.

I want to find a solution without enabling unloadInvisibleTiles option.

Is the only way to do this is through getPixelBounds()?

Edit: Added an example gist.

Upvotes: 3

Views: 1180

Answers (1)

YaFred
YaFred

Reputation: 10008

As far as I know, you have to go through getPixelBounds()

You can enumerate them with following code: xTile and yTile are what you are looking for

// get bounds, zoom and tileSize        
var bounds = map.getPixelBounds();
var zoom = map.getZoom();
var tileSize = 256;  


// get NorthWest and SouthEast points
var nwTilePoint = new L.Point(Math.floor(bounds.min.x / tileSize),
    Math.floor(bounds.min.y / tileSize));

var seTilePoint = new L.Point(Math.floor(bounds.max.x / tileSize),
    Math.floor(bounds.max.y / tileSize));

// get max number of tiles in this zoom level
var max = map.options.crs.scale(zoom) / tileSize; 

// enumerate visible tiles 
for (var x = nwTilePoint.x; x <= seTilePoint.x; x++) {
   for (var y = nwTilePoint.y; y <= seTilePoint.y; y++) {

      var xTile = (x + max) % max;
      var yTile = (y + max) % max;

      console.log('tile ' + xTile + ' ' + yTile);
    }
}

Upvotes: 3

Related Questions