find shortrst distance betseen two points on earth in csharp

To find the distance between two points on Earth, you can use the Haversine formula, which is based on the Great Circle Distance between two coordinates. Here is an implementation in C#:

main.cs
public static double Distance(double lat1, double lon1, double lat2, double lon2)
{
    const double R = 6371; // Radius of the earth in km

    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.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
    var distance = R * c; // Distance in km
    return distance;
}

private static double ToRadians(double degrees)
{
    return degrees * Math.PI / 180;
}
610 chars
19 lines

The inputs lat1, lon1, lat2, and lon2 are the latitude and longitude coordinates of the two points you want to find the distance between. The output is the distance in kilometers.

Note that this implementation assumes that the Earth is a perfect sphere with a radius of 6371 km. This is not completely accurate, as the Earth is oblate spheroidal in shape, but it is a good approximation for most practical purposes.

gistlibby LogSnag