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
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With