将两个坐标点转换为东西向和南北向的距离

Converting two coordinate points to distance in west-east-facing and north-south-facing direction

我正在尝试找出如何计算两点之间的 "west-east-facing" 距离和 "north-south-facing" 距离,分别给定两点的坐标(带有纬度和经度),以便找出线与北方方向不同的程度。 In short I need to calculate x and y in meters in order to get the degree of alpha, when x and y are given by longitude and latitude.

我知道 CLLocation 有一个函数可以计算两点之间的距离:

距离(从位置:CLLocation)->CLLocationDistance

并且我试图打开该函数的源代码以弄清楚如何分离这两个组件,但我没有找到如何打开该代码。

您可以将 point1 和 point2 转换为 MKMapPoint。它为您提供在 2D 平面中投影地图的坐标。然后你可以很容易地得到 x 和 y 的差异。使用简单的数学,你可以计算出 alpha 值。您可以使用 CLLocationCoordinate2D 初始化 MKMapPoint。

https://developer.apple.com/documentation/mapkit/mkmappoint

假设我们有:

let locationA = CLLocation(..)
let locationB = CLLocation(..)

我可能仍想使用 Apple 提供的功能并创建仅在纬度或经度上有所不同的新位置。类似于:

let latitudeA = CLLocation(latitude: locationA.latitude, longitude: locationA.longitude)
// notice I use latitude from B but KEEP longitude from A to keep them parallel)
let latitudeB = CLLocation(latitude: locationB.latitude, longitude: locationA.longitude)
let northSouthDistance = latitudeA.distance(from: latitudeB)

等等

你可以使用这个

func getDistanceAndAngle(positionA: CLLocation, positionB: CLLocation) -> (Float, Float, Float){

    let distanceInMeters = Float(positionA.distance(from: positionB)) // result is in meters
    print(distanceInMeters)
    //search for the degree
    let angle = bearingFromLocation(fromLocation: positionA.coordinate, toLocation: positionB.coordinate)
    print("ANGLE", angle)
    let xDistance = abs(distanceInMeters * cos(DegreesToRadians(degrees: angle)))
    let yDistance = abs(distanceInMeters * sin(DegreesToRadians(degrees: angle)))

    return (xDistance,yDistance,angle)
}


func bearingFromLocation(fromLocation:CLLocationCoordinate2D, toLocation: CLLocationCoordinate2D)-> Float{

    let lat1 = DegreesToRadians(degrees: Float(fromLocation.latitude))
    let lon1 = DegreesToRadians(degrees: Float(fromLocation.longitude))

    let lat2 = DegreesToRadians(degrees: Float(toLocation.latitude))
    let lon2 = DegreesToRadians(degrees: Float(toLocation.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)
    print("radian", radiansBearing)
    let degreesBearing = RadiansToDegrees(radians: radiansBearing)
    print("deg", degreesBearing)

    if (degreesBearing >= 0) {
        return degreesBearing
    } else {
        return degreesBearing + 360.0
    }
}

func DegreesToRadians(degrees: Float)->Float {return degrees * Float.pi / 180.0}
func RadiansToDegrees(radians: Float)->Float {return radians * 180.0/Float.pi}

备注: 角度是从北到东 所以北为 0 度,东为 90 度。 X 和 Y 始终为正。所以如果你想让它向左和向下变成负数,你可以尝试把使用度数变成正数。