Created
August 10, 2008 01:24
-
-
Save kastner/4711 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
#!/usr/bin/php | |
<?php | |
define("BASE32", "0123456789bcdefghjkmnpqrstuvwxyz"); | |
function geo_hash_decode($geo_hash) { | |
$ones_and_zeros = array_map("chr2bin", str_split($geo_hash, 1)); | |
$exploded = str_split(join($ones_and_zeros, ""), 1); | |
$l_l = array(0 => array(), 1 => array()); | |
foreach($exploded as $i => $o) { | |
$l_l[$i % 2][] = $o; | |
} | |
$lon = array2val($l_l[0], 180); | |
$lat = array2val($l_l[1], 90); | |
return(array("latitude" => $lat, "longitude" => $lon)); | |
} | |
function chr2bin($chr) { | |
$base32 = str_split(BASE32, 1); | |
$pos = array_search($chr, $base32); | |
return sprintf("%05b", $pos); | |
} | |
function bin2char($bin) { | |
$base32 = str_split(BASE32, 1); | |
return $base32[bindec($bin)]; | |
} | |
function array2val($array, $error) { | |
$val = 0; | |
$min = $error * -1; | |
$max = $error; | |
foreach ($array as $m) { | |
($m==0) ? $max = $val : $min = $val; | |
$val = $min + abs($max - $min) / 2; | |
//echo "min$min max:$max val:$val\n"; | |
} | |
return $val; | |
} | |
function geo_hash_encode($lat, $lon, $precision = 12) { | |
if ($precision > 12) { $precision = 12; } | |
if ($precision < 1) { $precision = 1; } | |
$string = ""; | |
$final = ""; | |
$b_lat = val2bin($lat, 90); | |
$b_lon = val2bin($lon, 180); | |
for ($i = 0; $i < max(sizeof($b_lat), sizeof($b_lon)); $i++) { | |
$string .= $b_lon[$i] . $b_lat[$i]; | |
} | |
foreach(str_split($string, 5) as $chunk) { | |
//echo "doing $chunk\n"; | |
$final .= bin2char($chunk); | |
} | |
return substr($final, 0, $precision); | |
} | |
function val2bin($target, $error) { | |
$val = 0; | |
$min = $error * -1; | |
$max = $error; | |
$moves = array(); | |
while ($i++ <= 30) { | |
if ($target > $val) { | |
$moves[] = 1; | |
$min = $val; | |
} | |
else { | |
$moves[] = 0; | |
$max = $val; | |
} | |
$val = $min + ($max - $min) / 2; | |
} | |
return $moves; | |
} | |
// val2bin(-5.60302734375, 180); | |
// geo_hash_decode("ezs42"); | |
// echo "\n"; | |
// | |
// geo_hash_decode("ezs4"); | |
// echo "\n"; | |
// | |
// geo_hash_decode("ezs"); | |
// echo "\n"; | |
// | |
// geo_hash_decode("e"); | |
// echo "\n"; | |
// geo_hash_decode("dpkpdcs81jpy"); | |
// | |
//geo_hash_encode(42.6049804688, -5.60302734375); | |
//geo_hash_decode("ezs42ebpbpbm"); | |
$c = "ezefd36yxyrb"; | |
$c = "6gkzwgjzn820"; | |
echo $c . "\n"; | |
$g = geo_hash_decode($c); | |
var_dump($g); | |
echo geo_hash_encode($g["latitude"], $g["longitude"]); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment