6

我正在开发一个指南针,它可以从我当前的位置指向对象的其他位置。目前我正在关注这个链接:Point to location using compass

我觉得在我当前位置与对象之间的指向是不正确的。谁能帮助我如何开发可以从我当前位置指向对象其他位置的指南针?

4

1 回答 1

1

要计算您的位置和目标位置之间的角度,您需要 4 个输入变量:

1) 当前位置(从核心位置获得)

2)目标位置(已知)

3) 当前航向(相对于真北,从核心位置获得)

4)方位角,真北与目标之间的角度,您可以使用以下代码获取它:

private func getBearing(point1: CLLocationCoordinate2D, point2: CLLocationCoordinate2D) -> Double {

    let lat1 = point1.latitude.degreesToRadians
    let lon1 = point1.longitude.degreesToRadians

    let lat2 = point2.latitude.degreesToRadians
    let lon2 = point2.longitude.degreesToRadians

    let dLon = lon2 - lon1

    let y = sin(dLon) * cos(lat2)
    let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)

    var radiansBearing = atan2(y, x)
    if radiansBearing < 0 {
        radiansBearing += 2 * Double.pi
    }

    return radiansBearing.radiansToDegrees
}

然后您可以使用以下代码计算您和目标之间的角度:

/// Compute the angle between two map points and the from point heading
/// returned angle is between 0 and 360 degrees
private func doComputeAngleBetweenMapPoints(
    fromHeading: CLLocationDirection,
    _ fromPoint: CLLocationCoordinate2D,
    _ toPoint: CLLocationCoordinate2D
) -> CLLocationDirection {
    let bearing = getBearing(point1: fromPoint, point2: toPoint)
    var theta = bearing - fromHeading
    if theta < 0 {
        theta += 360
    }
    return theta
}
于 2019-02-20T22:01:23.193 回答