You are here

public function GeoHash::write in geoPHP 8

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

Convert the geometry to geohash.

Parameters

Point $geometry:

Return value

string the geohash or null when the $geometry is not a Point

Overrides GeoAdapter::write

See also

GeoAdapter::write()

File

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

Class

GeoHash
PHP Geometry GeoHash encoder/decoder.

Code

public function write(Geometry $geometry, $precision = NULL) {
  if ($geometry
    ->isEmpty()) {
    return '';
  }
  if ($geometry
    ->geometryType() === 'Point') {
    return $this
      ->encodePoint($geometry, $precision);
  }
  else {

    // The geohash is the hash grid ID that fits the envelope
    $envelope = $geometry
      ->envelope();
    $geohashes = array();
    $geohash = '';
    foreach ($envelope
      ->getPoints() as $point) {
      $geohashes[] = $this
        ->encodePoint($point, 1.0E-7);
    }
    $i = 0;
    while ($i < strlen($geohashes[0])) {
      $char = $geohashes[0][$i];
      foreach ($geohashes as $hash) {
        if ($hash[$i] != $char) {
          return $geohash;
        }
      }
      $geohash .= $char;
      $i++;
    }
    return $geohash;
  }
}