Skip to content

Instantly share code, notes, and snippets.

@mourner
Created February 5, 2014 15:21
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mourner/8825883 to your computer and use it in GitHub Desktop.
Save mourner/8825883 to your computer and use it in GitHub Desktop.
Leaflet — get all tile URLs given geographic bounds, tile layer and zoom
function getTileUrls(bounds, tileLayer, zoom) {
var min = map.project(bounds.getNorthWest(), zoom).divideBy(256).floor(),
max = map.project(bounds.getSouthEast(), zoom).divideBy(256).floor(),
urls = [];
for (var i = min.x; i <= max.x; i++) {
for (var j = min.y; j <= max.y; j++) {
var coords = new L.Point(i, j);
coords.z = zoom;
urls.push(tileLayer.getTileUrl(coords));
}
}
return urls;
}
@fgrs
Copy link

fgrs commented Nov 13, 2014

what gets passed in as a second parameter tileLayer?

@johndpope
Copy link

johndpope commented Dec 12, 2016

@ted-piotrowski
Copy link

ted-piotrowski commented Oct 20, 2020

Screen Shot 2020-10-20 at 12 25 06 PM

If the map is zoomed out to a level (i.e. 0) where tiles need to be repeated, this code and xyz-affair library will return negative values for x and y. This will result in invalid tile urls because tiles with negative indexes don't exist. The solution here is to modulo using the zoom level to ensure the x and y values do not go outside the allowed values:

Allowed [x, y] values for each zoom level:

Zoom 0: [0, 0]
Zoom 1: [0, 0] [0, 1], [1, 0], [1, 1]
Zoom 2: ....
function getTileUrls(bounds, tileLayer, zoom) {
    var min = map.project(bounds.getNorthWest(), zoom).divideBy(256).floor(),
        max = map.project(bounds.getSouthEast(), zoom).divideBy(256).floor(),
        urls = [],
        mod = Math.pow(2, zoom);

    for (var i = min.x; i <= max.x; i++) {
        for (var j = min.y; j <= max.y; j++) {
            var x = (i % mod + mod) % mod;
            var y = (j % mod + mod) % mod;
            var coords = new L.Point(x, y);
            coords.z = zoom;
            urls.push(tileLayer.getTileUrl(coords));
        }
    }

    return urls;
}

The (x % mod + mod) % mod ensures negative numbers are treated correctly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment