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

时间:2014-11-18 15:34:46

标签: ios swift cllocation

我试图在仅限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)
}

我的atan2电话有关lvalue cgfloat或其他内容的错误...

2 个答案:

答案 0 :(得分:36)

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

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

答案 1 :(得分:5)

这不完全准确,但您可能正在寻找以下内容:

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
}

我挪用了this NSHipster article中的代码,该代码更详细地说明了它的错误。基本的问题是,它使用坐标,好像世界是平的(它不是,对吧?)。 Mattt的文章可以向您展示如何使用MKMapPoint而不是CLLocation来获取真实路线。