将两个坐标点转换为朝西和朝北的距离

时间:2019-02-11 18:08:37

标签: ios core-location cllocationmanager cllocation

我正在尝试找出如何分别在给定两点(经度和纬度)的坐标的情况下计算两点之间的“东西向”距离和“南北向”距离,为了找出线与北方向的不同程度。 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

我试图打开该函数的源代码,以便弄清楚如何将两个组件分开,但是我没有找到如何打开该代码的信。

3 个答案:

答案 0 :(得分:1)

您可以使用此

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始终为正。因此,如果要使其在左右方向上为负数,则可以尝试将使用度设置为正确。

答案 1 :(得分:0)

您可以将point1和point2转换为MKMapPoint。它为您提供了在2D平面中投影地图的坐标。然后,您可以轻松获得x和y的差。.并且,通过简单的数学运算,您可以计算出alpha值。您可以使用CLLocationCoordinate2D初始化MKMapPoint。

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

答案 2 :(得分:0)

假设我们有:

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)