encode static method

String encode({
  1. required LatLng latLng,
  2. required int codeLength,
})

Encode a latitude and longitude pair into a geohash string.

Implementation

static String encode({
  required LatLng latLng,
  required int codeLength,
}) {
  if (codeLength > 20 || (identical(1.0, 1) && codeLength > 12)) {
    //Javascript can only handle 32 bit ints reliably.
    throw ArgumentError('latitude and longitude are not precise enough to encode $codeLength characters');
  }
  final latitudeBase2 = (latLng.latitude + 90) * (pow(2.0, 52) / 180);
  final longitudeBase2 = (latLng.longitude + 180) * (pow(2.0, 52) / 360);
  final longitudeBits = (codeLength ~/ 2) * 5 + (codeLength % 2) * 3;
  final latitudeBits = codeLength * 5 - longitudeBits;
  var longitudeCode = (identical(1.0, 1)) //Test for javascript.
      ? (longitudeBase2 / (pow(2.0, 52 - longitudeBits))).floor()
      : longitudeBase2.floor() >> (52 - longitudeBits);
  var latitudeCode = (identical(1.0, 1)) //Test for javascript.
      ? (latitudeBase2 / (pow(2.0, 52 - latitudeBits))).floor()
      : latitudeBase2.floor() >> (52 - latitudeBits);

  final stringBuffer = <String>[];
  for (var localCodeLength = codeLength; localCodeLength > 0; localCodeLength--) {
    int bigEndCode;
    int littleEndCode;

    if (localCodeLength.isEven) {
      //Even slot. Latitude is more significant.
      bigEndCode = latitudeCode;
      littleEndCode = longitudeCode;
      latitudeCode >>= 3;
      longitudeCode >>= 2;
    } else {
      bigEndCode = longitudeCode;
      littleEndCode = latitudeCode;
      latitudeCode >>= 2;
      longitudeCode >>= 3;
    }
    final code = ((bigEndCode & 4) << 2) |
        ((bigEndCode & 2) << 1) |
        (bigEndCode & 1) |
        ((littleEndCode & 2) << 2) |
        ((littleEndCode & 1) << 1);
    stringBuffer.add(_base32NumberToChar[code]);
  }
  final buffer = StringBuffer()..writeAll(stringBuffer.reversed);
  return buffer.toString();
}