我正在开发一个指南针,可以从我当前的位置指向对象的其他位置。目前我关注此链接:Point to location using compass
我觉得指向我当前位置与对象之间的关系是不正确的。 任何人都可以帮我开发如何开发可以从我当前位置指向对象其他位置的指南针吗?
答案 0 :(得分:0)
要计算您的位置和目标位置之间的角度,您需要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
}