Core Location extensions for bearing and distance

Posted by Dave on February 3rd, 2009

As part of a recent iPhone project, I needed to find a point at a certain distance from one location in the direction of a second location.  I found the formulas I needed on Movable Type Ltd’s scripts page, and converted these into the appropriate Obj-C code to run on an iPhone using the iPhone SDK.

I’m posting the code with permission from Chris Veness of Movable Type Ltd., in case anyone else finds this useful.  The three functions have been created as a category implementation for the CLLocation class.

The functions are:

- (double)bearingInRadiansTowardsLocation:(CLLocation *)towardsLocation;

- (CLLocation *)newLocationAtDistance:(CLLocationDistance)atDistance alongBearingInRadians:(double)bearingInRadians;

- (CLLocation *)newLocationAtDistance:(CLLocationDistance)atDistance towardsLocation:(CLLocation *)towardsLocation;

You would use them as follows:

double theBearing = [theStartLocation bearingInRadiansTowardsLocation:theEndLocation];

CLLocation *theNewLocation = [theStartLocation newLocationAtDistance:150.0 alongBearingInRadians:4.0];

CLLocation *theNewLocation = [theStartLocation newLocationAtDistance:150.0 towardsLocation:theEndLocation];

…where theStartLocation and theEndLocation are existing CLLocation instances, and distances are in metres.

All you need to do to use these functions is to add both CLLocation+CLExtensions.h and CLLocation+CLExtensions.m to your XCode project, and then include CLLocation+CLExtensions.h at the top of any class in which you want to make use of the three extension functions mentioned above.

Note that the CLLocation instances returned by the second and third functions are owned by the calling code and will need to be released via [theNewLocation release] when you are done with them.

Many thanks to Chris for his permission to make these functions available.  The original JavaScript implementation is © 2002-2006 Chris Veness.



Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Very nice piece of work and thanks for sharing this information!

Hi Dave,
I just tried to use these extensions in a project, and for whatever reason, I had to make a few minor tweaks to get them to compile. Amended source can be downloaded here:
http://www.prehensile.co.uk/source/CLLocation+CLExtensions.zip

Hi Henry,

You’re right, there were a few errors in my original posted zip file. I’ve replaced my original file with your amended one, and it should work now. Thanks!