用于计算轴承w / Haversine功能的CLL位类别 [英] CLLocation Category for Calculating Bearing w/ Haversine function
问题描述
我正在尝试为CLLocation编写一个类别,以将轴承返回到另一个CLLocation。
I'm trying to write a category for CLLocation to return the bearing to another CLLocation.
我相信我做错了公式(calculous是不是我强大的西装)。返回的方位总是关闭。
I believe I'm doing something wrong with the formula (calculous is not my strong suit). The returned bearing is always off.
我一直在查看这个问题,并尝试应用所接受的更改作为正确答案及其引用的网页:
I've been looking at this question and tried applying the changes that were accepted as a correct answer and the webpage it references:
计算两个CLLocationCoordinate2D之间的方位
http:/ /www.movable-type.co.uk/scripts/latlong.html
感谢您的任何指示。我已经尝试合并其他问题的反馈,但我仍然没有得到一些东西。
Thanks for any pointers. I've tried incorporating the feedback from that other question and I'm still just not getting something.
谢谢
这是我的类别 -
----- CLLocation + Bearing.h
----- CLLocation+Bearing.h
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
@interface CLLocation (Bearing)
-(double) bearingToLocation:(CLLocation *) destinationLocation;
-(NSString *) compassOrdinalToLocation:(CLLocation *) nwEndPoint;
@end
--------- CLLocation + Bearing.m
---------CLLocation+Bearing.m
#import "CLLocation+Bearing.h"
double DegreesToRadians(double degrees) {return degrees * M_PI / 180;};
double RadiansToDegrees(double radians) {return radians * 180/M_PI;};
@implementation CLLocation (Bearing)
-(double) bearingToLocation:(CLLocation *) destinationLocation {
double lat1 = DegreesToRadians(self.coordinate.latitude);
double lon1 = DegreesToRadians(self.coordinate.longitude);
double lat2 = DegreesToRadians(destinationLocation.coordinate.latitude);
double lon2 = DegreesToRadians(destinationLocation.coordinate.longitude);
double dLon = lon2 - lon1;
double y = sin(dLon) * cos(lat2);
double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
double radiansBearing = atan2(y, x);
return RadiansToDegrees(radiansBearing);
}
推荐答案
你的代码对我来说似乎不错。该计算没有错。您没有指定结果的距离,但您可以尝试将您的弧度/度数转换器调整为:
Your code seems fine to me. Nothing wrong with the calculous. You don't specify how far off your results are, but you might try tweaking your radian/degrees converters to this:
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 you are getting negative bearings, add 2*M_PI
to the final result in radiansBearing (or 360 if you do it after converting to degrees). atan2 returns the result in the range -M_PI
to M_PI
(-180 to 180 degrees), so you might want to convert it to compass bearings, using something like the following code
if(radiansBearing < 0.0)
radiansBearing += 2*M_PI;
这篇关于用于计算轴承w / Haversine功能的CLL位类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!