Order Geofire Results from a Distance

I experimented with Geofire for iOS , but didn't seem to find a way to return the distance from the search position to the query circle. GFQueryResultBlock returns only the key and position. Am I right in assuming that I must calculate the distance myself?

Let's say I'm building a restaurant app nearby with Firebase and want to display the 20 nearest restaurants for users ordered by how close they are. I could create a round query, and then increase the radius of the loop search until I find 20 restaurants. Then calculate the distance for each of them and sort them before displaying them to the user. Is this a reasonable approach, given that the application does a lot of work to structure the data (calculate distance and sort)?

I noticed that the Geofire JavaScript request returns the distance from the center , but I assume that the versions of iOS and android are different from this.

+6
source share
1 answer

When you request Geofire, the corresponding results are automatically sorted in ascending order. Therefore, to get the distance, I just used the distanceFromLocation function: Here is 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!

+3
source

All Articles