a function for calculating distance between lat long in csharp

You can use the Haversine formula to calculate the distance between two points using their latitude and longitude. Here's an example function in C# that uses this formula:

main.cs
public static double Distance(double lat1, double lon1, double lat2, double lon2)
{
    const double earthRadius = 6371; // 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 = earthRadius * c;
    
    return distance;
}

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

To use the function, simply pass in the latitude and longitude of the two points you want to calculate the distance between:

main.cs
var distance = Distance(51.5074, -0.1278, 40.7128, -74.0060); // London to New York
Console.WriteLine(distance); // Output: 5572.169
133 chars
3 lines

gistlibby LogSnag