Calculate the distance between two points on the earth

by Morten 4/12/2006 11:45:49 AM

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.

/// <summary>
/// Calculates the distance between to lat/long points and returns the approximate distance in kilometers
/// </summary>
/// <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.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Comments are closed

Powered by BlogEngine.NET 1.4.5.0


Recent Comments

Comment RSS

About the author

Morten Nielsen Morten Nielsen
<--That's me
E-mail me Send mail

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2008