Search code examples
c#.netsql-serversqlgeographygeographic-distance

.NET Equivalent of SQL Server STDistance


I can use the following SQL to calculate the distance between a fixed location and the location against the venues in the database.

SELECT Location.STDistance(geography::Point(51, -2, 4326)) * 0.00062137119 FROM Venues

Please note the distance returned is in miles and the Location field is a geography type.

I was wondering what is the equivalent of this in .NET which would return the same values. This method would have the following signature:

public static double Distance(location1Latitude, location1Longitude, location2Latitude, location2Longitude) {
    return ...;
}

I know I could call the database method in .NET but I don't wish to do this. I'm hoping there is a formula to calculate the distance. Thanks


Solution

  • You would need to compute the Geographical distance to compute the distance manually. There are many different techniques and formulas to do this, each with different underlying assumptions (ie: a spherical earth, ellipsoidal earth, etc).

    A common option is the haversine formula, with a C# implementation available here.