Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getDistanceFrom Vs distanceFromLocation

Tags:

iphone

I'm having a problem with getDistanceFrom and distanceFromLocation. getDistanceFrom is deprecated iOS 4.1 and distanceFromLocation is not available in 3.1.3, how do I get around this problem.

Has anyone else come across this problem ?

My code at the moment is:

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;
        }

Depending on which iOS I compile with I'm getting 'invalid operands to binary' on the lines:

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

Regards, Stephen

like image 860
Stephen Avatar asked Sep 27 '10 13:09

Stephen


2 Answers

There's a blog post by Cédric Luthi which has a pretty good solution to this.

In short, you need to enter the following into your main.m and make sure to #import <objc/runtime.h> :

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

You can then use distanceFromLocation: on any OS.

like image 167
Tom Irving Avatar answered Nov 17 '22 14:11

Tom Irving


I use my own method. It is MUCH faster and can be used on both iOS 3.x and 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;
}

like image 11
Pavel Alexeev Avatar answered Nov 17 '22 15:11

Pavel Alexeev