为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用Firestore运行地理“附近”查询?

如何使用Firestore运行地理“附近”查询?

Firebase的新Firestore数据库本身是否支持基于位置的地理位置查询?即查找10英里内的帖子,还是找到50个最近的帖子?我看到有一些实时Firebase数据库的现有项目,例如geofire等项目,这些项目也可以改编成Firestore吗?
查看完整描述

3 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

更新:Firestore当前不支持实际的GeoPoint查询,因此尽管以下查询成功执行,但它仅按纬度而不是经度进行过滤,因此将返回许多附近的结果。最好的解决方案是使用geohash。要了解自己如何做类似的事情,请观看此视频。


这可以通过创建一个小于查询的边界框来完成。至于效率,我不能说。


请注意,应检查纬度/经度偏移〜1英里的精度,但这是一种快速的方法:


SWIFT 3.0版本


func getDocumentNearBy(latitude: Double, longitude: Double, distance: Double) {


    // ~1 mile of lat and lon in degrees

    let lat = 0.0144927536231884

    let lon = 0.0181818181818182


    let lowerLat = latitude - (lat * distance)

    let lowerLon = longitude - (lon * distance)


    let greaterLat = latitude + (lat * distance)

    let greaterLon = longitude + (lon * distance)


    let lesserGeopoint = GeoPoint(latitude: lowerLat, longitude: lowerLon)

    let greaterGeopoint = GeoPoint(latitude: greaterLat, longitude: greaterLon)


    let docRef = Firestore.firestore().collection("locations")

    let query = docRef.whereField("location", isGreaterThan: lesserGeopoint).whereField("location", isLessThan: greaterGeopoint)


    query.getDocuments { snapshot, error in

        if let error = error {

            print("Error getting documents: \(error)")

        } else {

            for document in snapshot!.documents {

                print("\(document.documentID) => \(document.data())")

            }

        }

    }


}


func run() {

    // Get all locations within 10 miles of Google Headquarters

    getDocumentNearBy(latitude: 37.422000, longitude: -122.084057, distance: 10)

}


查看完整回答
反对 回复 2019-10-06
?
四季花海

TA贡献1811条经验 获得超5个赞

自@monkeybonkey首次提出此问题以来,已经引入了一个新项目。该项目称为GEOFirestore。


使用此库,您可以在一个圆圈内执行查询,例如查询文档:


  const geoQuery = geoFirestore.query({

    center: new firebase.firestore.GeoPoint(10.38, 2.41),

    radius: 10.5

  });

您可以通过npm安装GeoFirestore。您将必须单独安装Firebase(因为它是GeoFirestore的对等依赖项):


$ npm install geofirestore firebase --save


查看完整回答
反对 回复 2019-10-06
  • 3 回答
  • 0 关注
  • 615 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信