Created
April 27, 2020 11:38
-
-
Save dselivanov/77526fed90ca97a53a6d423e313708fb to your computer and use it in GitHub Desktop.
This file contains 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
# converts slippy map XYZ tile to quadkey | |
# https://docs.microsoft.com/en-us/bingmaps/articles/bing-maps-tile-system | |
as_binary = function(x){ | |
tmp = rev(as.integer(intToBits(x))) | |
id = seq_len(match(1, tmp, length(tmp)) - 1) | |
tmp[-id] | |
} | |
deg2num = function(lat_deg, lon_deg, zoom) { | |
lat_rad = lat_deg * pi /180 | |
n = 2.0 ^ zoom | |
xtile = floor((lon_deg + 180.0) / 360.0 * n) | |
ytile = floor((1.0 - log(tan(lat_rad) + (1 / cos(lat_rad))) / pi) / 2.0 * n) | |
c(xtile, ytile) | |
} | |
# reference JavaScript implementations | |
# https://developer.here.com/documentation/traffic/dev_guide/common/map_tile/topics/quadkeys.html | |
tileXYToQuadKey = function(xTile, yTile, z) { | |
quadKey = "" | |
for (i in z:1) { | |
digit = 0 | |
mask = bitwShiftL(1, i - 1) | |
xtest = as_binary(bitwAnd(xTile, mask)) | |
if(any(xtest)) { | |
digit = digit + 1 | |
} | |
ytest = as_binary(bitwAnd(yTile, mask)) | |
if(any(ytest)) { | |
digit = digit + 2 | |
} | |
quadKey = paste0(quadKey, digit) | |
} | |
quadKey | |
} | |
stopifnot(tileXYToQuadKey(35210, 21493, 16) == "1202102332221212") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment