haversine formula for lat long in csharp

Here's an example of how to calculate the distance between two points on Earth using the Haversine formula in C#:

main.cs
public static double Haversine(double lat1, double lon1, double lat2, double lon2, double radius = 6371)
{
    var dLat = ToRadians(lat2 - lat1);
    var dLon = ToRadians(lon2 - lon1);
    var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(ToRadians(lat1)) 
            * Math.Cos(ToRadians(lat2)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
    var c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)));
    return radius * c;
}

private static double ToRadians(double angle)
{
    return Math.PI * angle / 180.0;
}
515 chars
15 lines

This method takes in four parameters, which are the latitude and longitude of the two points, and an optional radius of the Earth (default value is 6,371 km). It returns the distance between the two points in the specified unit (km in this example).

To use this method, you can simply call it with the latitude and longitude of the two points:

main.cs
double distance = Haversine(32.050382, 34.766149, 37.774929, -122.419416);
75 chars
2 lines

This will calculate the distance between Tel Aviv, Israel and San Francisco, USA.

gistlibby LogSnag