【问题标题】:How to query nearest users in Firebase with Swift?如何使用 Swift 在 Firebase 中查询最近的用户?
【发布时间】:2017-02-07 14:10:06
【问题描述】:

我想找到离我最近的用户。 (例如长达 5 公里)我在 firebase 数据库中的节点如下结构,

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

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

【问题讨论】:

  • 如果您不想使用 Geofire,另一种选择是查询任一方向(纬度/经度)内 5 公里范围内的所有用户,这将为您提供比 5 公里半径范围内更多的用户。然后,使用较小的用户子集,进行 CLLocation 距离比较。您最终将不得不为那些不合格的用户(即在经度和纬度 5 公里外的角落里的用户)选择它,但您肯定会直接获得直接在 5 公里外的用户 N/S或 E/W。

标签: ios swift firebase firebase-realtime-database cllocationdistance


【解决方案1】:

我强烈建议使用 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)'")
})

【讨论】:

  • pod 'GeoFire', '~> 1.1' 我收到这些错误:Podfile 需要 Firebase - Podfile.lock 需要 Firebase (= 3.11.0) Podfile.lock 需要 - Firebase (~> 2.1) GeoFire (1.1.0) 需要 Firebase (~> 2.1) 我该怎么办? /跨度>
  • 你必须用桥头手动拖入,见github.com/firebase/geofire-objc/issues/…
猜你喜欢
  • 2016-10-14
  • 1970-01-01
  • 2017-06-05
  • 2016-08-04
  • 2018-03-18
  • 1970-01-01
  • 2017-03-25
  • 2018-10-30
  • 1970-01-01
相关资源
最近更新 更多