Cocoalicious & Co.

Enjoy Programming

0 notes

Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.
Antoine de Saint-Exupéry

0 notes

Distance between 2 places on Earth in C on the iPhone

Today I was working on an augmented reality app and I had to update the annotations in the AR so that the distance would get updated every - let’s say - 20 meters.

The distance from the object was in the JSON I was getting back from the server, so I didn’t need any calculation. However, I needed to calculate the distance from the last user location in order to spare the server unnecessary requests and send one only if the user had moved 20 meters or more.

So here’s what I did :

1. I first got a NSTimer running every 5 seconds to check the new user location.

Keep an instance variable of the reference user location, let’s say :

`CLLocationCoordinate2D userLocationCoordinate;`

2. I then calculated the distance between this point and the previous user location. Here’s how to do it :

```//Don't forget to import math.h
#import <math.h>

//To convert degrees to radians
#define DEGREES_TO_RADIANS(__ANGLE__) ((__ANGLE__) / 180.0 * M_PI)

double DistanceBetweenTwoPlaces(double lon1, double lat1, double lon2, double lat2) {
//Earth radius in kilometers
double earthRadius = 6371;

//calculate the delta longitude and latitude
double deltaLon = DEGREES_TO_RADIANS(lon2 - lon1);
double deltaLat = DEGREES_TO_RADIANS(lat2 - lat1);

//Use of the Haversine function
double a = pow(sin(deltaLat/2), 2) + cos(lat1) * cos(lat2) * pow(sin(deltaLon/2), 2);
//Use of atan2() isntead of atan() to simplify the case where the denominator would be equal to zero when using the equation with atan()
double centralAngle = 2 * atan2(sqrt(a), sqrt(1-a));
//Multiply by 1000 to get the distance in meters
double distance = b * earthRadius * 1000;

return distance;
}
```

3. Then if the distance is equal or superior to 20 meters, update self.userLocationCoordinate to the new user location and do whatever you have to do to get the data updated (in my case server request) and reload the annotations.

There you go. I hope this tutorial will help some of you!