簡體   English   中英

Flutter & firebase 通過 geohash 獲取文檔

[英]Flutter & firebase get docs by geohash

我正在嘗試獲取基於 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 ZC1C425268E68385D1AB5074C17A94F1 返回錯誤的值,但我不確定我做錯了什么

位置 A geohash = 'gcqd6' 位置 B geohash = 'gcqd6'

getGeohashRange返回的上限和下限 = 下限:“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(),
      );
}

原來有一個插件可以真正幫助解決這個問題。 這個文檔有一些信息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());
}

上面的文檔中有一個“位置”字段的示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM