问题描述
|
如何在iPhone地图应用程序中计算两个POI(兴趣点)的坐标之间的角度(以度为单位)?
解决方法
我猜想您尝试计算两个兴趣点(POI)的坐标之间的度数。
计算大圆弧:
+(float) greatCircleFrom:(CLLocation*)first
to:(CLLocation*)second {
int radius = 6371; // 6371km is the radius of the earth
float dLat = second.coordinate.latitude-first.coordinate.latitude;
float dLon = second.coordinate.longitude-first.coordinate.longitude;
float a = pow(sin(dLat/2),2) + cos(first.coordinate.latitude)*cos(second.coordinate.latitude) * pow(sin(dLon/2),2);
float c = 2 * atan2(sqrt(a),sqrt(1-a));
float d = radius * c;
return d;
}
另一个选择是假装您在笛卡尔坐标上(更快,但在长距离上并非没有错误):
+(float)angleFromCoordinate:(CLLocationCoordinate2D)first
toCoordinate:(CLLocationCoordinate2D)second {
float deltaLongitude = second.longitude - first.longitude;
float deltaLatitude = second.latitude - first.latitude;
float angle = (M_PI * .5f) - atan(deltaLatitude / deltaLongitude);
if (deltaLongitude > 0) return angle;
else if (deltaLongitude < 0) return angle + M_PI;
else if (deltaLatitude < 0) return M_PI;
return 0.0f;
}
如果要以度而不是弧度为单位,则必须应用以下转换:
#define RADIANS_TO_DEGREES(radians) ((radians) * 180.0 / M_PI)
,您正在此处计算从一个点到另一个的“轴承”。此网页上有很多公式,以及距离和跨轨误差等其他许多地理量:
http://www.movable-type.co.uk/scripts/latlong.html
公式采用多种格式,因此您可以轻松转换为iPhone所需的任何语言。还有JavaScript计算器,因此您可以测试自己的代码得到与他们相同的答案。
,如果其他解决方案对您不起作用,请尝试以下操作:
- (int)getInitialBearingFrom:(CLLocation *)first
to:(CLLocation *)second
{
float lat1 = [self degreesToRad:first.coordinate.latitude];
float lat2 = [self degreesToRad:second.coordinate.latitude];
float lon1 = [self degreesToRad:first.coordinate.longitude];
float lon2 = [self degreesToRad:second.coordinate.longitude];
float dLon = lon2 - lon1;
float y = sin (dLon) * cos (lat2);
float x1 = cos (lat1) * sin (lat2);
float x2 = sin (lat1) * cos (lat2) * cos (dLon);
float x = x1 - x2;
float bearingRadRaw = atan2f (y,x);
float bearingDegRaw = bearingRadRaw * 180 / M_PI;
int bearing = ((int) bearingDegRaw + 360) % 360; // +- 180 deg to 360 deg
return bearing;
}
对于最终轴承,只需将初始轴承从端点移至起点,然后将其反转即可(使用θ=(θ+ 180)%360)。
您需要以下两个助手:
-(float)radToDegrees:(float)radians
{
return radians * 180 / M_PI;
}
-(float)degreesToRad:(float)degrees
{
return degrees * M_PI /180;
}