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

Jee*_*eef 23 cllocation ios swift

我正在尝试计算仅限swift的代码中两个CLLocation点之间的方位.我遇到了一些困难,并假设这是一个非常简单的功能.堆栈溢出似乎没有列出任何内容.

func d2r(degrees : Double) -> Double {
    return degrees * M_PI / 180.0
}

func RadiansToDegrees(radians : Double) -> Double {
    return radians * 180.0 / M_PI
}


func getBearing(fromLoc : CLLocation, toLoc : CLLocation) {

    let fLat = d2r(fromLoc.coordinate.latitude)
    let fLng = d2r(fromLoc.coordinate.longitude)
    let tLat = d2r(toLoc.coordinate.latitude)
    let tLng = d2r(toLoc.coordinate.longitude)

    var a = CGFloat(sin(fLng-tLng)*cos(tLat));
    var b = CGFloat(cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(fLng-tLng))

    return atan2(a,b)
}
Run Code Online (Sandbox Code Playgroud)

我的atan2调用关于lvalue cgfloat或其他东西我收到错误...

Mar*_*n R 41

这是Objective-C解决方案

可以很容易地翻译成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)
}
Run Code Online (Sandbox Code Playgroud)

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


Guy*_*gus 7

这并不完全准确,但是您可能正在寻找一些类似的东西:

func XXRadiansToDegrees(radians: Double) -> Double {
    return radians * 180.0 / M_PI
}

func getBearingBetweenTwoPoints(point1 : CLLocation, point2 : CLLocation) -> Double {
    // Returns a float with the angle between the two points
    let x = point1.coordinate.longitude - point2.coordinate.longitude
    let y = point1.coordinate.latitude - point2.coordinate.latitude

    return fmod(XXRadiansToDegrees(atan2(y, x)), 360.0) + 90.0
}
Run Code Online (Sandbox Code Playgroud)

我从NSHipster这篇文章中获得了代码,代码更详细地介绍了问题所在。基本的问题是,它使用的坐标就像世界是平坦的(不是,是吧?)。Mattt的文章可以向您展示如何使用MKMapPoints而不是CLLocations 获得真实的方向。