【问题标题】:Ordering Geofire results on Distance按距离排序 Geofire 结果
【发布时间】:2016-12-15 21:20:47
【问题描述】:

我一直在尝试使用Geofire for iOS,但似乎找不到任何方法来返回圆形查询中与搜索位置的距离。 GFQueryResultBlock 只返回键和位置。我是否正确假设我必须自己计算距离?

假设我正在使用 Firebase 制作一个附近的餐厅应用,并且想要显示离用户最近的 20 家餐厅,并按距离排序。我可以创建一个圆形查询,然后通过循环增加搜索半径,直到找到 20 家餐厅。然后计算每个距离并在将它们显示给用户之前对其进行排序。这是一种合理的方法吗,因为在应用程序中进行了大量工作来构建数据(计算距离和排序)?

我注意到javascript Geofire 查询return distance from the center,但我猜iOS 和android 版本与此不同。

【问题讨论】:

  • 这种方法没有害处。而且,如果您使用 iOS 提供的排序例程之一,它会非常快。我对我的一个应用程序使用相同的方法,并且从未遇到任何问题。随着 Geofire 逐步返回结果,所有后续插入都在 log(n) 时间内发生,这是非常有效的。我猜你不是在处理数千个对象。
  • Firebase geofire-js:如何获取静态(固定)位置附近的键列表:stackoverflow.com/questions/43632746/…

标签: ios firebase firebase-realtime-database geofire


【解决方案1】:

当您从 Geofire 查询时,相关结果会自动按升序排列。所以为了得到距离,我只使用 distanceFromLocation 函数: 这是我的代码:

func getGeoFirePlaces(){

    let geofireRef = FIRDatabase.database().reference().child("testForGeofire")
    let geoFire  = GeoFire(firebaseRef: geofireRef)
    //geoFireRef is pointing to a firebase reference where I previously set all  places' location 
    let userPosition = CLLocation(latitude: 32.0776067, longitude: 34.78912)
    let circleQuery = geoFire.queryAtLocation(userPosition, withRadius: 2)

    circleQuery.observeEventType(.KeyEntered, withBlock: { (key: String!, location: CLLocation!) in
        print("Key '\(key)' entered the search area and is at location '\(location)'")

        //getting distance of each Place return with the callBack
        let distanceFromUser = userPosition.distanceFromLocation(location)
        print(distanceFromUser)
    })

}

希望对您有所帮助!

【讨论】:

  • 我对这个答案的有效性有些怀疑。请,你能指出我提到相关结果按升序自动排序的文档吗?你的意思是什么顺序?距离?谢谢
  • 不,我正在使用它,但它没有给出排序输出。它给出的结果是基于附近首先存储的内容。