geoHashForLocation method

String geoHashForLocation(
  1. GeoPoint location, {
  2. int precision = _GEOHASH_PRECISION,
})

Generates a geohash of the specified precision/string length from the latitude, longitude pair, specified as an array.

@param location The latitude, longitude pair to encode into a geohash. @param precision The length of the geohash to create. If no precision is specified, the global default is used. @returns The geohash of the inputted location.

Implementation

String geoHashForLocation(GeoPoint location,
    {int precision = _GEOHASH_PRECISION}) {
  validateLocation(location);
  if (precision != null) {
    if (precision is int == false || precision.isNaN) {
      throw ('precision must be an integer');
    } else if (precision <= 0) {
      throw ('precision must be greater than 0');
    } else if (precision > 22) {
      throw ('precision cannot be greater than 22');
    }
  }
  var latitudeRange = {'min': -90.0, 'max': 90.0};
  var longitudeRange = {'min': -180.0, 'max': 180.0};
  String hash = '';
  int hashVal = 0;
  int bits = 0;
  bool even = true;
  while (hash.length < precision) {
    var val = even ? location.longitude : location.latitude;
    var range = even ? longitudeRange : latitudeRange;
    double mid = (range['min']! + range['max']!) / 2;

    if (val > mid) {
      hashVal = (hashVal << 1) + 1;
      range['min'] = mid;
    } else {
      hashVal = (hashVal << 1) + 0;
      range['max'] = mid;
    }
    even = !even;
    if (bits < 4) {
      bits++;
    } else {
      bits = 0;
      hash += _BASE32[hashVal];
      hashVal = 0;
    }
  }
  return hash;
}