我正在尝试获取帖子,并在用户到达某个半径时将其打印到控制台。我怎么能这么快。
swift - 从Firebase按位置快速获取帖子-LMLPHP

最佳答案

这是我用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)
  }
}

10-06 07:39