在距离上订购Geofire结果

时间:2016-08-09 17:48:40

标签: ios firebase firebase-realtime-database geofire

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

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

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

1 个答案:

答案 0 :(得分:4)

当您从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)
    })

}

希望这有帮助!

相关问题