Haversine Distance Formula

I’m working on an analysis tool for GPS data in C# which needs to calculate the distance between two geographic coordinates, and I chose the Haversine formula (explanation).  So I figured I’d share my implementation:

        public class Point
        {
            public double Latitude { get; private set; }
            public double Longitude{ get; private set; }

            public Point(double latitude, double longitude)
            {
                Latitude = latitude;
                Longitude = longitude;
            }
        }

        public static double ToRadian(double angle)
        {
            return Math.PI * angle / 180.0;
        }

        public static double HaversineDistance(Point a, Point b)
        {
            const double radius = 3956.6 * 5280; // in feet
            double latitude = ToRadian(b.Latitude - a.Latitude) / 2;
            double longitude = ToRadian(b.Longitude - a.Longitude) / 2;

            double x = Math.Sin(latitude) * Math.Sin(latitude) + Math.Sin(longitude) * Math.Sin(longitude) *
                                                                 Math.Cos(ToRadian(a.Latitude)) * Math.Cos(ToRadian(b.Latitude));
            double y = 2 * Math.Atan2(Math.Sqrt(x), Math.Sqrt(1 - x));

            return radius * y;
        }

To change the units (these are in feet), change the radius (source: Wolfram Alpha).

This entry was posted in C#, Math and tagged , . Bookmark the permalink.
  • Delicious
  • Facebook
  • Reddit
  • StumbleUpon
  • Twitter
  • RSS Feed
  • Google
  • Digg

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>