Flutter & Firebase通过geohash获取文档

zc0qhyus  于 2023-04-22  发布在  Flutter
关注(0)|答案(2)|浏览(119)

我试图根据geohash的上下限获取文档。“位置A”是用户的位置,我们试图在firebase中找到“位置A”范围内的其他位置。我正在学习本教程
https://levelup.gitconnected.com/nearby-location-queries-with-cloud-firestore-e7f4a2f18f9d
并在这个网站上查询
https://www.movable-type.co.uk/scripts/geohash.html
“位置A”的坐标是52.462570419161594, -2.0120335164758725,“位置B”的坐标是52.46648448588268, -1.9841125656313279。它们彼此非常接近,因此,使用下面的代码,我假设在firebase查询中,当从“位置A”的geohash查询时,它会返回“位置B”,但这并没有发生,这是因为getGeohashRange函数返回了错误的值,但我不确定我是什么。我做错了
位置A geohash = 'gcqd6'位置B geohash = 'gcqd6'
getGeohashRange返回的upper & lower = lower:“mpt5mf52n18z”上部:“mptmvc2wncyc”
这是代码& Firebase查询

// Get the geohash upper & lower bounds
GeoHashRange getGeohashRange({
  required double latitude,
  required double longitude,
  double distance = 12, // miles
}) {
  double lat = 0.0144927536231884; // degrees latitude per mile
  double lon = 0.0181818181818182; // degrees longitude per mile

  double lowerLat = latitude - lat * distance;
  double lowerLon = longitude - lon * distance;

  double upperLat = latitude + lat * distance;
  double upperLon = longitude + lon * distance;

  GeoHasher geo = GeoHasher();

  var lower = geo.encode(lowerLat, lowerLon);
  var upper = geo.encode(upperLat, upperLon);

  return GeoHashRange(lower: lower, upper: upper);
}

class GeoHashRange {
  late String upper;
  late String lower;

  GeoHashRange({
    required this.upper,
    required this.lower,
  })
}


// Query firebase for locations
Stream<List<Garage>> getLocalGarages(Position position) {
  GeoHashRange range = getGeohashRange(
    latitude: position.latitude,
    longitude: position.longitude,
  );

  var ref = _db
      .collection('garages')
      .where("geohash", isGreaterThan: range.upper)
      .where("geohash", isLessThan: range.lower);

  return ref.snapshots().map(
        (list) =>
            list.docs.map((doc) => Garage.fromJson(doc.data())).toList(),
      );
}
uxhixvfz

uxhixvfz1#

将您的where Firestore请求更改为:

.where("geohash", isLessThanOrEqualTo: range.upper)
    .where("geohash", isGreaterThanOrEqualTo: range.lower)
hgtggwj0

hgtggwj02#

事实证明,有一个插件,实际上可以帮助这一点。这个文档有一些信息https://firebase.google.com/docs/firestore/solutions/geoqueries#java,这是插件https://pub.dev/packages/geoflutterfire
这是我的新密码

Stream<List<Garage>> localGarages(Position position) {
  var ref = _db.collection('garages');

  GeoFirePoint center =
      geo.point(latitude: position.latitude, longitude: position.longitude);
  double radiusInKM = 20;

  return geo
      .collection(collectionRef: ref)
      .within(center: center, radius: radiusInKM, field: 'position')
      .map((x) => x.map((e) => Garage.fromJson(e.data()!)).toList());
}

在上面的文档中有一个“位置”字段的示例

相关问题