Ordering Geofire results on Distance
Asked Answered
G

1

7

I've been experimenting with Geofire for iOS but can't seem to find any way of returning the distance from the search position in a circle query. The GFQueryResultBlock only returns the key and position. Am I right in assuming that I have to calculate the distance myself?

Let's say I am making a nearby restaurant app with Firebase, and want to display the 20 closest restaurants to the user, ordered by how close they are. I could create a circle query and then increase the search radius via a loop until I find 20 restaurants. Then calculate the distance for each one and sort them before displaying them to the user. Is this a reasonable approach, given that a large amount of work is being done in the app to structure the data (calculating distance & sorting)?

I've noticed that javascript Geofire queries return distance from the center, but I guess the iOS and android versions are different from this.

Gilkey answered 9/8, 2016 at 17:48 Comment(2)
There is no harm in the approach. And if you use one of the sorting routines provided by iOS, it's very fast. I use the same approach for one of my apps and never faced any issue. As Geofire returns results incrementally, all subsequent insertions happen in log(n) time which is quite efficient. I am guess you are not dealing with objects in the order of thousands.Manducate
Firebase geofire-js : how to get list of keys of near by static(fixed) locations : #43633246Coffer
C
5

When you are querying from Geofire, relevant results are automatically ordered by ascending order. So in order to get the distance , Im just using the distanceFromLocation function: Here my code:

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

}

Hope this help!

Cannikin answered 6/12, 2016 at 14:58 Comment(2)
I have some doubts regarding the validity of this answer. Please, can you point me to the documentation that mentions that relevant results are automatically ordered by ascending order? And by what order do you mean? distance? ThanksBake
No, I am using it and it not gives sorted output.. its gives result on basis what stored first in that nearby.Confirmed

© 2022 - 2024 — McMap. All rights reserved.