You are here

private function GeoHash::encodePoint in geoPHP 7

Same name and namespace in other branches
  1. 8 geoPHP/lib/adapters/GeoHash.class.php \GeoHash::encodePoint()

@author algorithm based on code by Alexander Songe <a@songe.me>

Parameters

Point $point:

Return value

string geohash

See also

https://github.com/asonge/php-geohash/issues/1

1 call to GeoHash::encodePoint()
GeoHash::write in geoPHP/lib/adapters/GeoHash.class.php
Convert the geometry to geohash.

File

geoPHP/lib/adapters/GeoHash.class.php, line 133

Class

GeoHash
PHP Geometry GeoHash encoder/decoder.

Code

private function encodePoint($point, $precision = NULL) {
  if ($precision === NULL) {
    $lap = strlen($point
      ->y()) - strpos($point
      ->y(), ".");
    $lop = strlen($point
      ->x()) - strpos($point
      ->x(), ".");
    $precision = pow(10, -max($lap - 1, $lop - 1, 0)) / 2;
  }
  $minlat = -90;
  $maxlat = 90;
  $minlon = -180;
  $maxlon = 180;
  $latE = 90;
  $lonE = 180;
  $i = 0;
  $error = 180;
  $hash = '';
  while ($error >= $precision) {
    $chr = 0;
    for ($b = 4; $b >= 0; --$b) {
      if ((1 & $b) == (1 & $i)) {

        // even char, even bit OR odd char, odd bit...a lon
        $next = ($minlon + $maxlon) / 2;
        if ($point
          ->x() > $next) {
          $chr |= pow(2, $b);
          $minlon = $next;
        }
        else {
          $maxlon = $next;
        }
        $lonE /= 2;
      }
      else {

        // odd char, even bit OR even char, odd bit...a lat
        $next = ($minlat + $maxlat) / 2;
        if ($point
          ->y() > $next) {
          $chr |= pow(2, $b);
          $minlat = $next;
        }
        else {
          $maxlat = $next;
        }
        $latE /= 2;
      }
    }
    $hash .= $this->table[$chr];
    $i++;
    $error = min($latE, $lonE);
  }
  return $hash;
}