Last active
June 13, 2019 17:03
-
-
Save key/daba42e5072d04b9de74223d00b4f0bd to your computer and use it in GitHub Desktop.
Arduino implementation of quadkey
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
#include <math.h> | |
/** | |
以下を参考に実装 | |
https://cttr.jp/2019/04/10/post-453/ | |
https://github.com/buckhx/QuadKey/blob/master/quadkey/tile_system.py | |
*/ | |
struct PixelXY { | |
int x; | |
int y; | |
}; | |
struct TileXY { | |
double x; | |
double y; | |
}; | |
double clip(double val, double minVal, double maxVal) { | |
return min(max(val, minVal), maxVal); | |
} | |
String latlon_to_quadkey(double lat, double lon, int zoom_level) { | |
// geo to pixel xy | |
// normalize values | |
lat = clip(lat, -85.05112878, 85.05112878); | |
lon = clip(lon, -180.0, 180.0); | |
double x = (lon + 180) / 360; | |
double sin_lat = sin(lat * M_PI / 180); | |
double y = 0.5 - log((1 + sin_lat) / (1 - sin_lat)) / (4 * M_PI); | |
int map_size = 256 << zoom_level; | |
int pixel_x = clip(x * map_size + 0.5, 0, map_size - 1); | |
int pixel_y = clip(y * map_size + 0.5, 0, map_size - 1); | |
PixelXY xy = {pixel_x, pixel_y}; | |
// pixel xy to tile xy | |
TileXY tile = {xy.x / 256, xy.y / 256}; | |
int tile_x = tile.x; | |
int tile_y = tile.y; | |
String quadkey = ""; | |
for (int i = 0; i < zoom_level; i++) { | |
int bi = zoom_level - i; | |
int digit = 0; | |
int mask = 1 << (bi - 1); | |
if ((tile_x & mask) != 0 ) { | |
digit += 1; | |
} | |
if ((tile_y & mask) != 0) { | |
digit += 2; | |
} | |
quadkey += String(digit); | |
} | |
return quadkey; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment