Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering Geofire results on Distance

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.

like image 845
user3053470 Avatar asked Aug 09 '16 17:08

user3053470


1 Answers

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!

like image 185
jerem Avatar answered Oct 24 '22 13:10

jerem