$geo = encode_geohash(30.63578, 104.031601, 12); //神马时候做成个php扩展把!
echo $geo;
print_r(decode_geohash($geo));
function encode_geohash($latitude, $longitude, $deep)
{
$BASE32 = '0123456789bcdefghjkmnpqrstuvwxyz';
$bits = array(16,8,4,2,1);
$lat = array(-90.0, 90.0);
$lon = array(-180.0, 180.0);
$bit = $ch = $i = 0;
$is_even = 1;
$i = 0;
$mid;
$geohash = '';
while($i < $deep)
{
if ($is_even)
{
$mid = ($lon[0] + $lon[1]) / 2;
if($longitude > $mid)
{
$ch |= $bits[$bit];
$lon[0] = $mid;
}else{
$lon[1] = $mid;
}
} else{
$mid = ($lat[0] + $lat[1]) / 2;
if($latitude > $mid)
{
$ch |= $bits[$bit];
$lat[0] = $mid;
}else{
$lat[1] = $mid;
}
}
$is_even = !$is_even;
if ($bit < 4)
$bit++;
else {
$i++;
$geohash .= $BASE32[$ch];
$bit = 0;
$ch = 0;
}
}
return $geohash;
}
function decode_geohash($geohash)
{
$geohash = strtolower($geohash);
$BASE32 = '0123456789bcdefghjkmnpqrstuvwxyz';
$bits = array(16,8,4,2,1);
$lat = array(-90.0, 90.0);
$lon = array(-180.0, 180.0);
$hashlen = strlen($geohash);
$is_even = 1;
for($i = 0; $i < $hashlen; $i++ )
{
$of = strpos($BASE32,$geohash[$i]);
for ($j=0; $j<5; $j++) {
$mask = $bits[$j];
if ($is_even) {
$lon[!($of&$mask)] = ($lon[0] + $lon[1])/2;
} else {
$lat[!($of&$mask)] = ($lat[0] + $lat[1])/2;
}
$is_even = !$is_even;
}
}
$point = array( 0 => ($lat[0] + $lat[1]) / 2, 1 => ($lon[0] + $lon[1]) / 2);
return $point;
}
转载于:https://my.oschina.net/xming4321/blog/134194