获取iOS中两个坐标之间距离的垂直和水平分量

时间:2016-05-18 04:03:51

标签: ios swift math cllocation

我试图在swift中创建一个函数,准确计算任何位置与地球原点的垂直和水平距离(纬度:0,经度:0)。我知道iOS有distanceFromLocation功能,但这给了我直接位置。我正在寻找的是该方向的水平和垂直分量。我试着提出自己的解决方案,但是当我根据我得到的水平和垂直分量测试直接距离时,它并没有与实际距离相匹配。这是我的职责:

func distanceFromOrigin(location:CLLocation) {

    let lat = location.coordinate.latitude
    let lon = location.coordinate.longitude

    let earthOriginLocation = CLLocation(coordinate: CLLocationCoordinate2DMake(0.0, 0.0), altitude: CLLocationDistance(0.0), horizontalAccuracy: kCLLocationAccuracyBestForNavigation, verticalAccuracy: kCLLocationAccuracyBestForNavigation, timestamp: NSDate())

    var horDistance = earthOriginLocation.distanceFromLocation(CLLocation(latitude: 0.0, longitude: location.coordinate.longitude))
    var verDistance = earthOriginLocation.distanceFromLocation(CLLocation(latitude: location.coordinate.latitude, longitude: 0.0))

    let overallDistance = earthOriginLocation.distanceFromLocation(location)

    if lat < 0 {
        print("Object is South of Equator")
        verDistance *= -1
    } else if lat > 0 {
        print("Object is North of Equator")
    } else {
        print("Object is at the Equator")
    }
    if lon < 0 {
        print("Object is West of Prime Meridian")
        horDistance *= -1
    } else if lon > 0 {
        print("Object is East of Prime Meridian")
    } else {
        print("Object is at the Prime Meridian")
    }

    print("Vertical Distance: \(verDistance)")
    print("Horizontal Distance: \(horDistance)")
    print("Overall Distance: \(overallDistance)")

    //Test to see if vertical and horizontal distances are accurate compared to actual distance.
    print("Test: \(sqrt((pow(horDistance, 2.0)) + (pow(verDistance, 2.0))))")

}

谢谢!

1 个答案:

答案 0 :(得分:5)

您的代码很好,但您的测试错误。

你错过了地球不是平面所以你正在考虑的直角三角形放在大地水准面上,并且斜边比平方边和更大。

我建议您手动执行几项测试,以确保结果看起来很逼真,而不是在曲面上挖掘这种几何图形。

次要注意事项:如果点彼此非常接近,则测试可以通过,因为在这种情况下,地球表面的曲率对计算的影响最小。