# calculating distance between two point Iphone

I'm creating an app for the iphone and eventually the Android. I'm trying to calulcate the distance between two points gotten from LocationInfo.latitude and LocationInfo.longitude. does this look right?

``````   latitude1 = LocationInfo.latitude;
longitude1 = LocationInfo.longitude;

//much later, when the Latitude and longitude are different values we do this:

latitude2 = LocationInfo.latitude;
longitude2 = LocationInfo.longitude;

//then we need the code to figure out how far apart they are:

lat3 = latitude2 - latitude1;
long3 =longitude2 - longitude1;

// then is the distnace between them this? (a2 + b2 = c2?)

dist1 = (lat3 *lat3) + (long3*long3);
finaldist = Mathf.Sqrt(dist1);

``````

is that the best way to get the distance between two GPS coordinates or is there a better way? does this work for the android and the iphone?

That is certainly one way of doing it, but perhaps not the best. I'm not a sailor, so I know nothing about maps and such. But I've searched a bit around for this and this is the first hit:

http://www.movable-type.co.uk/scripts/latlong.html

And as I thought. The calculations you made gives a straight line from A to B, if it was a flat map. However, the world is not flat (or it was once, so why not again? :-) ). The world is round, so to get the correct distance you need to take this into consideration. The link I gave you should help you with the last piece of the puzzle :)

public void Calc(float lat1, float lon1, float lat2, float lon2)
{

``````        var R = 6378.137; // Radius of earth in KM
var dLat = lat2 * Mathf.PI / 180 - lat1 * Mathf.PI / 180;
var dLon = lon2 * Mathf.PI / 180 - lon1 * Mathf.PI / 180;
float a = Mathf.Sin(dLat / 2) * Mathf.Sin(dLat / 2) +
Mathf.Cos(lat1 * Mathf.PI / 180) * Mathf.Cos(lat2 * Mathf.PI / 180) *
Mathf.Sin(dLon / 2) * Mathf.Sin(dLon / 2);
var c = 2 * Mathf.Atan2(Mathf.Sqrt(a), Mathf.Sqrt(1 - a));
var d = R * c;
//d= d * 1000f; // meters

Text singleText = GameObject.Find("Button").GetComponentInChildren<Text>();
// write result to the button's text
singleText.text = d.ToString("F3")+"km";
}
``````