12. April 2006 10:45
Here is a small C# method for calculating distances between two longitude/latitude points based on Movable Type's article on the subject. Since the earth isn't perfectly round, and since I've found several values for the approximate radius of the earth, this method is only approximate, but should be sufficiently accurate for most applications.
/// Calculates the distance between to lat/long points and returns the approximate distance in kilometers
/// <param name="from">Point in long/lat decimal degrees</param>
/// <param name="to">Point in long/lat decimal degrees</param>
/// <returns>Distance in kilometers</returns>
private double CalcDistance(Point from, Point to)
double rad = 6371; //Earth radius in Km
//Convert to radians
double p1X = from.X / 180 * Math.PI;
double p1Y = from.Y / 180 * Math.PI;
double p2X = to.X / 180 * Math.PI;
double p2Y = to.Y / 180 * Math.PI;
return Math.Acos(Math.Sin(p1Y) * Math.Sin(p2Y) +
Math.Cos(p1Y) * Math.Cos(p2Y) * Math.Cos(p2X - p1X)) * rad;
If you want the distance returned in something else than kilometers, change the radius to whatever unit you would like the output unit to be in.
I have successfully incorporated this in a SharpMap-based application for doing nearest-object searches in a map. It is fun to see how the earth-curvate is taken into account; -this is particularily visible towards the poles in a flat projected map.