我试图在仅Swift代码中计算两个CLLocation点之间的方位角。我遇到了一些困难,并假设这是一个非常简单的功能。堆栈溢出似乎没有列出任何内容。
func d2r(degrees : Double) -> Double { return degrees * M_PI / 180.0 } func RadiansToDegrees(radians : Double) -> Double { return radians * 180.0 / M_PI } func getBearing(fromLoc : CLLocation, toLoc : CLLocation) { let fLat = d2r(fromLoc.coordinate.latitude) let fLng = d2r(fromLoc.coordinate.longitude) let tLat = d2r(toLoc.coordinate.latitude) let tLng = d2r(toLoc.coordinate.longitude) var a = CGFloat(sin(fLng-tLng)*cos(tLat)); var b = CGFloat(cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(fLng-tLng)) return atan2(a,b) }
我的ltan2调用关于左值cgfloat或其他错误…
这是一个Objective-C解决方案
您的代码对我来说似乎不错。没事的没错。您没有指定结果有多远,但是您可以尝试将弧度/度转换器转换为:
double DegreesToRadians(double degrees) {return degrees * M_PI / 180.0;}; double RadiansToDegrees(double radians) {return radians * 180.0/M_PI;};
如果得到负方位角,2*M_PI则以radiansBearing 添加到最终结果中(如果转换为度数,则添加为360)。atan2将结果返回的范围-M_PI为M_PI(-180至180度),因此您可能需要使用以下代码将其转换为罗盘方位
if(radiansBearing < 0.0) radiansBearing += 2*M_PI;
可以轻松地翻译成Swift:
func degreesToRadians(degrees: Double) -> Double { return degrees * .pi / 180.0 } func radiansToDegrees(radians: Double) -> Double { return radians * 180.0 / .pi } func getBearingBetweenTwoPoints1(point1 : CLLocation, point2 : CLLocation) -> Double { let lat1 = degreesToRadians(degrees: point1.coordinate.latitude) let lon1 = degreesToRadians(degrees: point1.coordinate.longitude) let lat2 = degreesToRadians(degrees: point2.coordinate.latitude) let lon2 = degreesToRadians(degrees: point2.coordinate.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) return radiansToDegrees(radians: radiansBearing) }
结果类型是Double因为这是所有位置坐标的存储方式(CLLocationDegrees是的类型别名Double)。
Double
CLLocationDegrees