1

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.

iamburak
  • 3,508
  • 4
  • 34
  • 65
  • 2
    Another option if you don't want to use Geofire would be to query all users who are withing 5km either direction (latitude / longitude), which would give you more users than are within the 5km radius. Then, with that smaller subset of users, do the CLLocation distance comparison. You would end up having to di it for users who don't make the cut (i.e. users in the corner who are 5km away in latitude and longitude), but you would be sure to get users who are directly 5km away directly N/S or E/W. – wottle Feb 07 '17 at 14:54

1 Answers1

8

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)'")
})
Andrew Brooke
  • 12,073
  • 8
  • 39
  • 55
  • `pod 'GeoFire', '~> 1.1'` I'm getting these errors: `Firebase` required by `Podfile` - `Firebase (= 3.11.0)` required by `Podfile.lock` - `Firebase (~> 2.1)` required by `GeoFire (1.1.0)` What should I do? – iamburak Feb 07 '17 at 21:26
  • You have to drag in manually with a bridge header, see https://github.com/firebase/geofire-objc/issues/48#issuecomment-225471865 – Peter de Vries Feb 08 '17 at 00:04