How to query nearest users in Firebase with Swift?

前端 未结 1 1134
终归单人心
终归单人心 2020-12-16 08:26

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:         


        
相关标签:
1条回答
  • 2020-12-16 09:31

    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)'")
    })
    
    0 讨论(0)
提交回复
热议问题