如何使用 Swift 在 Firebase 中查询最近的用户? [英] How to query nearest users in Firebase with Swift?

查看:18
本文介绍了如何使用 Swift 在 Firebase 中查询最近的用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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: _

有什么办法可以在该范围内获得准确的用户.否则,我应该使用 CLLocation distance 方法检查他们的每个用户是否离我最近的位置.

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.

推荐答案

我强烈推荐使用 Geofire 对于这样的事情.

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

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

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

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

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

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

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

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

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

这篇关于如何使用 Swift 在 Firebase 中查询最近的用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆