快速从Firebase按位置获取帖子

时间:2018-11-01 23:29:07

标签: swift firebase firebase-realtime-database

我正在尝试获取帖子,并在用户进入某种程度的半径时将其打印到控制台。我该如何迅速做到这一点。 Firebase Database

1 个答案:

答案 0 :(得分:0)

这是我写的Swift中的一个小结构,让您使用Haversine formula 计算两个坐标之间的距离(以km为单位)。

示例

let london = Coordinate(long: -0.118092, lat: 51.509865)
let paris = Coordinate(long: 2.3522219, lat: 48.856614)

print(london.distance(to: paris)) // ~343.43km
print(london == paris) // false
print(london) // 51.509865,-0.118092
print(paris) // 48.856614,2.3522219

代码

import Foundation

public struct Coordinate: CustomStringConvertible, Equatable {
  // Earth radius in km
  private static let radiusEarth = 6371.0

  public typealias Distance = Double

  public let lon: Double
  public let lat: Double

  public init(long: Double, lat: Double) {
    self.lon = long
    self.lat = lat
  }

  public static func == (lhs: Coordinate, rhs: Coordinate) -> Bool {
    return lhs.lon == rhs.lon && lhs.lat == rhs.lat
  }

  public var description: String {
    return "\(lat),\(lon)"
  }

  // Haversine formula
  public func distance(to other: Coordinate) -> Distance {
    let dLat = deg2rad(other.lat - lat)
    let dLon = deg2rad(other.lon - lon)
    let a =
      sin(dLat / 2) * sin(dLat / 2) +
      cos(deg2rad(lat)) * cos(deg2rad(other.lat)) *
      sin(dLon / 2) * sin(dLon / 2)
    let c = 2 * atan2(sqrt(a), sqrt(1 - a))
    return Coordinate.radiusEarth * c
  }

  private func deg2rad(_ deg: Double) -> Double {
    return deg * (.pi / 180.0)
  }
}