如何运行地理“附近"用firestore查询? [英] How to run a geo "nearby" query with firestore?

查看:11
本文介绍了如何运行地理“附近"用firestore查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 firebase 的新 Firestore 数据库本身是否支持基于位置的地理查询?即查找 10 英里内的帖子,或查找最近的 50 个帖子?

Does the new firestore database from firebase natively support location based geo queries? i.e. Find posts within 10 miles, or find the 50 nearest posts?

我看到有一些现有的实时 Firebase 数据库项目,例如 geofire-这些项目是否也适用于 Firestore?

I see that there are some existing projects for the real-time firebase database, projects such as geofire- could those be adapted to firestore as well?

推荐答案

更新:Firestore 目前不支持实际的 GeoPoint 查询,所以当下面的查询成功执行时,它只按纬度过滤,而不是按经度过滤,因此会返回许多不在附近的结果.最好的解决方案是使用 geohashes.要了解如何自己做类似的事情,请观看此视频.

UPDATE: Firestore does not support actual GeoPoint queries at present so while the below query executes successfully, it only filters by latitude, not by longitude and thus will return many results that are not nearby. The best solution would be to use geohashes. To learn how to do something similar yourself, have a look at this video.

这可以通过创建一个小于大于查询的边界框来完成.至于效率,我无话可说.

This can be done by creating a bounding box less than greater than query. As for the efficiency, I can't speak to it.

请注意,应该检查大约 1 英里的经纬度偏移的准确性,但这里有一个快速的方法:

Note, the accuracy of the lat/long offset for ~1 mile should be reviewed, but here is a quick way to do this:

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)
}

这篇关于如何运行地理“附近"用firestore查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆