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



我想找到离我所在位置最近的用户。(例如,最多5公里)我的节点在火球数据库中,如下面的结构,

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

有没有办法在那个半径范围内得到确切的用户。否则,我应该使用CLLocation distance方法检查每个用户离我最近的位置。

我强烈建议使用Geofire进行类似的操作。

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

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

最新更新