Ent*_*ean 5 mobile ios swift compass mobile-development
我正在开发一个指南针,可以从我当前的位置指向对象的其他位置.目前我正在关注此链接:使用指南针指向位置
我觉得指向我当前位置与对象之间是不正确的.任何人都可以帮我如何开发指南针,可以从我当前的位置指向对象的其他位置?
要计算您的位置和目标位置之间的角度,您需要 4 个输入变量:
1)当前位置(从Core Location获取)
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
}
Run Code Online (Sandbox Code Playgroud)
然后您可以使用以下代码计算您和目标之间的角度:
/// 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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
709 次 |
| 最近记录: |