Last active
October 9, 2015 16:54
-
-
Save pramsey/f9ac2489d034d6a9f403 to your computer and use it in GitHub Desktop.
Mercator Hash Key
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 <stdio.h> | |
#include <stdlib.h> | |
#include <math.h> | |
static char *base16 = "0123456789abcdef"; | |
char *mercator_hash(double x, double y, int precision) | |
{ | |
double quad_width = 20037508.34; | |
double cx = 0.0; | |
double cy = 0.0; | |
char bits[] = {8,4,2,1}; | |
char *hash = malloc(precision+1); | |
int i = 0, bit = 0, ch = 0, is_x = 1; | |
while (i < precision) | |
{ | |
if (is_x) | |
{ | |
quad_width /= 2.0; | |
printf("[%d] resolution: %g meters\n", i, quad_width); | |
if (x >= cx) | |
{ | |
ch |= bits[bit]; | |
cx += quad_width; | |
} | |
else | |
{ | |
cx -= quad_width; | |
} | |
} | |
else | |
{ | |
if (y >= cy) | |
{ | |
ch |= bits[bit]; | |
cy += quad_width; | |
} | |
else | |
{ | |
cy -= quad_width; | |
} | |
} | |
is_x = !is_x; | |
if (bit < 3) | |
{ | |
bit++; | |
} | |
else | |
{ | |
hash[i++] = base16[ch]; | |
bit = ch = 0; | |
} | |
} | |
// printf("resolution: %g meters\n", quad_width); | |
hash[i] = '\0'; | |
return hash; | |
} | |
int main(int argc, char** argv) | |
{ | |
/* | |
* echo "-126 45" | proj "+init=epsg:3857" | |
*/ | |
double x = -14026255.84; | |
double y = 5621521.49; | |
int precision = 12; | |
char *hash; | |
if ( argc == 3 ) | |
{ | |
x = atof(argv[1]); | |
y = atof(argv[2]); | |
} | |
if ( argc == 4 ) | |
{ | |
precision = atoi(argv[3]); | |
} | |
hash = mercator_hash(x, y, precision); | |
printf("%s\n", hash); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment