flutter_geo_hash 0.0.7
flutter_geo_hash: ^0.0.7 copied to clipboard
Geohash encoding, decoding and neighbors, with Firestore geoquery bounds and distance helpers for Dart and Flutter. Compatible with Firebase geofire-common.
import 'package:flutter_geo_hash/flutter_geo_hash.dart';
void main() {
final geoHash = GeoHashUtils();
// 1. Compute the geohash to store alongside each location.
const places = {
'Buckingham Palace': GeoHashPoint(51.5014, -0.1419),
'Windsor Castle': GeoHashPoint(51.4839, -0.6044),
'Brighton Pier': GeoHashPoint(50.8169, -0.1367),
'Cambridge': GeoHashPoint(52.2053, 0.1218),
};
final geohashes = {
for (final MapEntry(key: name, value: location) in places.entries)
name: geoHash.geoHashForLocation(location),
};
print('Stored geohashes:');
geohashes.forEach((name, hash) => print(' $name: $hash'));
// 2. Compute the geohash ranges covering 50 km around central London.
const center = GeoHashPoint(51.5074, -0.1278);
const radiusInM = 50 * 1000.0;
final bounds = geoHash.geohashQueryBounds(center, radiusInM);
print('Ranges to query:');
for (final range in bounds) {
print(' from ${range[0]} to ${range[1]}');
}
// 3. A database query returns every place whose geohash is in a range.
// Ranges are rectangles, so discard the places outside the circle.
print('Query results:');
for (final MapEntry(key: name, value: hash) in geohashes.entries) {
final matched = bounds.any((range) =>
hash.compareTo(range[0]) >= 0 && hash.compareTo(range[1]) <= 0);
if (!matched) {
continue;
}
final location = places[name]!;
final kilometers = geoHash.distanceBetween(center, location);
final verdict = geoHash.isWithinRadius(center, location, radiusInM)
? 'within 50 km'
: 'false positive, discarded';
print(' $name: ${kilometers.toStringAsFixed(1)} km, $verdict');
}
// 4. Decode a geohash and list the cells around it.
final cell = geohashes['Buckingham Palace']!.substring(0, 6);
print('Cell $cell:');
print(' bounds: ${geoHash.decodeGeoHashBounds(cell)}');
print(' center: ${geoHash.decodeGeoHash(cell)}');
geoHash.geoHashNeighbors(cell).forEach((direction, neighbor) {
print(' ${direction.name} neighbor: $neighbor');
});
}