Created
February 5, 2014 15:21
-
-
Save mourner/8825883 to your computer and use it in GitHub Desktop.
Leaflet — get all tile URLs given geographic bounds, tile layer and zoom
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
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
what gets passed in as a second parameter tileLayer?