Recently I had to calculate the distance between 2 GPS coordinates. Theres a fair bit of help online about how to do this but I though I would share my implementation of the Haversine method.

public double GetDistance(double latitude1, double longitude1, 
                                    double latitude2, double longitude2)
{
    double earthRadiusMiles = 3963;
    double distance = 0;

    // convert degrees to radians
    latitude1 = latitude1 * Math.PI / 180;
    longitude1 = longitude1 * Math.PI / 180;

    latitude2 = latitude2 * Math.PI / 180;
    longitude2 = longitude2 * Math.PI / 180;

    // check the points are not the same
    if (latitude1 != latitude2 && longitude1 != longitude2)
    {
        distance = Math.Sin(latitude1) * Math.Sin(latitude2)
                 + Math.Cos(latitude1) * Math.Cos(latitude2)
                 * Math.Cos(longitude2 - longitude1);

        distance = earthRadiusMiles
                    * (-1 * Math.Atan(distance / Math.Sqrt(1 - distance * distance))
                    + Math.PI / 2);
    }

    return distance;
}
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Slashdot
  • Technorati
  • Twitter
  • I did something similar back in 2002! Here's my implementation: http://segdeha.com/e/haversine...

    I was never very confident I got it all right. What do you think?

  • richchetwynd

    Sorry about the super slow reply, I missed this one while travelling..

    I just tried your formula and compared the results with mine and the distances come out the same. So I'm not 100% sure how accurate this formula is but we are definitely on the same page.

blog comments powered by Disqus