atan2(y,x)在180°处具有不连续性,其顺时针切换到-180°..0°.
如何将值范围映射到0°.360°?
这是我的代码:
CGSize deltaPoint = CGSizeMake(endPoint.x - startPoint.x, endPoint.y - startPoint.y);
float swipeBearing = atan2f(deltaPoint.height, deltaPoint.width);
Run Code Online (Sandbox Code Playgroud)
在给定startPoint和endPoint两个XY点结构的情况下,我正在计算滑动触摸事件的方向.该代码适用于iPhone,但任何支持atan2f()的语言都可以.
感谢您的帮助,包括一般解决方案和代码.
更新:我将erikkallen的答案变成了一个具有漂亮的长变量名的函数,所以我将在6个月后理解它.也许它会帮助其他一些iPhone noob.
float PointPairToBearingDegrees(CGPoint startingPoint, CGPoint endingPoint)
{
CGPoint originPoint = CGPointMake(endingPoint.x - startingPoint.x, endingPoint.y - startingPoint.y); // get origin point to origin by subtracting end from start
float bearingRadians = atan2f(originPoint.y, originPoint.x); // get bearing in radians
float bearingDegrees = bearingRadians * (180.0 / M_PI); // convert to degrees
bearingDegrees = (bearingDegrees > 0.0 ? bearingDegrees : (360.0 + …Run Code Online (Sandbox Code Playgroud) 我正在尝试计算仅限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)
}
Run Code Online (Sandbox Code Playgroud)
我的atan2调用关于lvalue cgfloat或其他东西我收到错误...
我实施了http://www.movable-type.co.uk/scripts/latlong.html中的"方位"公式.但它似乎非常不准确 - 我怀疑我的实施中有些错误.你能帮我找到它吗?我的代码如下:
protected static double bearing(double lat1, double lon1, double lat2, double lon2){
double longDiff= lon2-lon1;
double y = Math.sin(longDiff)*Math.cos(lat2);
double x = Math.cos(lat1)*Math.sin(lat2)-Math.sin(lat1)*Math.cos(lat2)*Math.cos(longDiff);
return Math.toDegrees((Math.atan2(y, x))+360)%360;
}
Run Code Online (Sandbox Code Playgroud)