getDistanceFrom Vs distanceFromLocation

时间:2010-09-27 13:30:38

标签: iphone

我遇到了getDistanceFrom和distanceFromLocation的问题。不推荐使用getDistanceFrom iOS 4.1和distanceFromLocation在3.1.3中不可用,我该如何解决这个问题。

还有其他人遇到过这个问题吗?

目前我的代码是:

CLLocationDistance kilometers;
        if ([currentLocation respondsToSelector: @selector(distanceFromLocation:)])
        {
            kilometers = [currentLocation distanceFromLocation:previousLocation] / 1000;
        }
        else
        {
            //kilometers = [currentLocation getDistanceFrom:previousLocation] / 1000;
            kilometers = [currentLocation performSelector: @selector(getDistanceFrom:) withObject: previousLocation] / 1000;
        }

取决于我编译的iOS,我在行上得到'无效操作数为二进制':

kilometers = [currentLocation distanceFromLocation:previousLocation] / 1000;
            kilometers = [currentLocation performSelector: @selector(getDistanceFrom:) withObject: previousLocation] / 1000;

此致 斯蒂芬

2 个答案:

答案 0 :(得分:14)

CédricLuthi有一个blog post,它有一个非常好的解决方案。

简而言之,您需要在main.m中输入以下内容并确保#import <objc/runtime.h>

Method getDistanceFrom = class_getInstanceMethod([CLLocation class], @selector(getDistanceFrom:));
class_addMethod([CLLocation class], @selector(distanceFromLocation:), method_getImplementation(getDistanceFrom), method_getTypeEncoding(getDistanceFrom));

然后,您可以在任何操作系统上使用distanceFromLocation:

答案 1 :(得分:11)

我使用自己的方法。它速度更快,可以在iOS 3.x和iOS 4.x上使用。


- (double)distanceFrom:(CLLocationCoordinate2D)locationA to:(CLLocationCoordinate2D)locationB

{
    double R = 6368500.0; // in meters

    double lat1 = locationA.latitude*M_PI/180.0;
    double lon1 = locationA.longitude*M_PI/180.0;
    double lat2 = locationB.latitude*M_PI/180.0;
    double lon2 = locationB.longitude*M_PI/180.0;

    return acos(sin(lat1) * sin(lat2) + 
                cos(lat1) * cos(lat2) *
                cos(lon2 - lon1)) * R;
}