Monday, December 08, 2008

Haversine formula

I'm sure I've been through this calculation before somewhere....

And it kind of made me sad that today instead of trying to work out for myself how to get from lat and long to x and y... I just googled a solution.

Here were some of the better (quicker to understand) answers in C#
The first also contains some excellent unit tests - good on him :)

My own eventual code merged the two together....


/// Calculates the distance between two points of latitude and longitude.
/// Great Link - http://www.movable-type.co.uk/scripts/latlong.html
/// lat1 - First coordinate.
/// long1 - First coordinate.
/// lat2 - Second coordinate.
/// long2 - Second coordinate.
/// unitsOfLength - Sets the return value unit of length - m for metres, k for kilometres, anything else for (non-mautical)miles
/// the distance
public static Double Distance(double lat1, double lon1, double lat2, double lon2, char unitsOfLength)
{
var theta = lon1 - lon2;

var distance = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) +
Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) *
Math.Cos(deg2rad(theta));

distance = Math.Acos(distance);
distance = rad2deg(distance);
distance = distance * 60 * 1.1515;

if (unitsOfLength == 'k')
distance = distance * 1.609344/*_MilesToKilometers*/;

else if (unitsOfLength == 'm')
distance = distance * 1609.344/*_MilesToKilometers*/;

return (distance);
}

private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}

private static double rad2deg(double rad) {
return (rad / Math.PI * 180.0);
}

No comments:

Post a Comment