【问题标题】:Firebase: Query by nearest locationFirebase:按最近的位置查询
【发布时间】:2018-10-30 23:35:12
【问题描述】:

Firebase 可以使用 Geopoint 对象存储文档。 https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/GeoPoint

但是我们不能在不同的字段上使用范围过滤器,这对于位置查询是必要的。

据我了解,一年前有使用 Geofire 进行此类查询的功能 Query for nearby locations

但现在它已经过时并且无法正常工作。

目前的解决方案是什么?

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    您可以使用GeoPoint Firestore 对象和GreatherThan 子句与LessThan 一起查询。您应该添加自己的准确度,而不是仅使用一英里的距离。

    fun Query.getNearestLocation(latitude: Double, longitude: Double, distance: Double): Query {
        // ~1 mile of lat and lon in degrees
        val lat = 0.0144927536231884
        val lon = 0.0181818181818182
    
        val lowerLat = latitude - (lat * distance)
        val lowerLon = longitude - (lon * distance)
    
        val greaterLat = latitude + (lat * distance)
        val greaterLon = longitude + (lon * distance)
    
        val lesserGeopoint = GeoPoint(lowerLat, lowerLon)
        val greaterGeopoint = GeoPoint(greaterLat, greaterLon)
    
        val docRef = FirebaseFirestore.getInstance().collection("locations")
        return docRef
                .whereGreaterThan("location", lesserGeopoint)
                .whereLessThan("location", greaterGeopoint)
    }
    

    此代码是由 Ryan Lee 在this post 上制作的代码的 Kotlin 翻译

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多