Quadkeys
Specifying the grid location of a map tile in terms of zoom level, column and row as described under The Mercator Projection is easy to understand and intuitive in practise. However, the grid is a two-dimensional array and as such does not offer efficient storage and retrieval. A better solution is a one-dimensional array, where each item is uniquely addressable by a single value. This is made possible by quadkeys, which combine the zoom level, column and row information for a tile in a one value.
In fact, a quadkey is a string containing a numeric value. The value is obtained by interleaving the bits of the row and column coordinates of a tile in the grid at the given zoom level, then converting the result to a base-4 number (the leading zeros are retained). The length of a quadkey string (the number of digits/characters) equals the zoom level of the tile.
For example, we can obtain the quadkey for a map tile in column 3 and row 5 at zoom level 5 as follows:
// Convert the column (x) and row (y) values
// to their binary (b) equivalents:
x = 3 -> 011b
y = 5 -> 101b
// Interleave the binary values (b), convert the
// combined result to a base-4 (q) number and
// finally convert that to a string:
quadkey = 100111b -> 213q -> "213"
The code below shows a JavaScript implementation of the algorithm that calculates quadkeys. The inputs are the coordinates of the a map tile and the zoom level. The return value is a string containing the quadkey. The lower part of the code block shows the function called to calculate a quadkey for zoom level 16, which is also the length of the output string shown on the last line.
--- input ---
xTile: 35210 // Column
yTile: 21493 // Row
z: 16 // Zoom Level
--- JavaScript ---
function tileXYToQuadKey(xTile, yTile, z) {
var quadKey = "";
for (var i = z; i > 0; i--) {
var digit = "0",
mask = 1 << (i - 1);
if ((xTile & mask) != 0) {
digit++;
}
if ((yTile & mask) != 0) {
digit = digit + 2;
}
quadKey += digit;
} // for i return quadKey;
return quadKey;
}
quadKey = tileXYToQuadKey(35210, 21493, 16);
--- output ---
quadKey = "1202102332221212"
Note that when using a quadkey address, you cannot specify the size or format of the map tile image. The response always includes an image that measures 256 x 256 pixels and the format is png32
.