且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算Swift中两个CLLocation点之间的方位

更新时间:2023-02-02 07:58:16

这是一个Objective-C解决方案

Here is an Objective-C solution

  • CLLocation Category for Calculating Bearing w/ Haversine function

可轻松转换为Swift:

which can easily be translated to Swift:

func degreesToRadians(degrees: Double) -> Double { return degrees * .pi / 180.0 }
func radiansToDegrees(radians: Double) -> Double { return radians * 180.0 / .pi }

func getBearingBetweenTwoPoints1(point1 : CLLocation, point2 : CLLocation) -> Double {

    let lat1 = degreesToRadians(degrees: point1.coordinate.latitude)
    let lon1 = degreesToRadians(degrees: point1.coordinate.longitude)

    let lat2 = degreesToRadians(degrees: point2.coordinate.latitude)
    let lon2 = degreesToRadians(degrees: point2.coordinate.longitude)

    let dLon = lon2 - lon1

    let y = sin(dLon) * cos(lat2)
    let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)
    let radiansBearing = atan2(y, x)

    return radiansToDegrees(radians: radiansBearing)
}

结果类型是 Double 因为这是所有位置坐标都是
存储的方式( CLLocationDegrees Double 的类型别名。

The result type is Double because that is how all location coordinates are stored (CLLocationDegrees is a type alias for Double).