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

问题描述 投票:1回答:3

我试图找出如何计算两个点之间的“西向东”距离和“南北朝向”距离,给出两点的坐标(纬度和经度),以便找出该线与北方向不同的程度。 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

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

ios core-location cllocationmanager cllocation
3个回答
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总是正面的。因此,如果你想让它向左和向下都是负面的,你可以尝试使用度来使其正确。


0
投票

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

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


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)

等等

© www.soinside.com 2019 - 2024. All rights reserved.