如何使用Swift查询Firebase中最近的用户?

我想找到最近的用户到我的位置。 (例如最多5km)我的firebase数据库中的节点如下面的结构,

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

是否有任何方法可以获得该半径内的确切用户。 否则,我应该使用CLLocation distance方法检查每个用户最近的位置。

我强烈建议使用Geofire这样的东西。

要进行设置,您的数据结构会略有变化。 您仍然可以在用户上存储lat / lng,但您还会创建一个名为users_locations的新Firebase表

您的users_locations表将通过Geofire填充,看起来像这样

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

通常,这是您在Geofire中存储位置的方式,但您可以将其设置为在创建用户对象/更新位置时保存。

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

当您在users_locations保存位置时,可以使用GFQuery查询特定范围内的所有用户。

 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)'") })