How to query nearest users in Firebase with Swift?

2019-01-25 00:40发布

问题:

I want to find nearest users to my location. (For example up to 5km) My nodes in firebase database like below structure,

+ users
  + user_id0
    - latitude: _
    - longitude: _

Is there any way getting exact users in that radius. Otherwise I should check each user of them nearest position or not to me using CLLocation distance method.

回答1:

I'd highly recommend using Geofire for something like this.

To set it up, your data structure will slightly change. You can still store lat/lng on your users, but you will also create a new Firebase table called something like users_locations

Your users_locations table will be populated through Geofire, and will look something like this

users_locations
  user_id0:
    g: 5pf666y
    l:
      0: 40.00000
      1: -74.00000

In general, this is how you would store a location in Geofire, but you can set it up to save whenever your user object is created / updates location.

let geofireRef = FIRDatabase.database().reference().child("users_locations")
let geoFire = GeoFire(firebaseRef: geofireRef)
geoFire.setLocation(CLLocation(latitude: lat, longitude: lng), forKey: "user_id0")

When you've saved your locations in users_locations, you can then use a GFQuery to query for all the users in a certain range.

let center = CLLocation(latitude: yourLat, longitude: yourLong)
var circleQuery = geoFire.queryAtLocation(center, withRadius: 5)

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