11

I need to find the distance between 2 coordinates in .NET core. I've tried using the below mentioned code,

var sCoord = new GeoCoordinate(sLatitude, sLongitude); var eCoord = new GeoCoordinate(eLatitude, eLongitude);

return sCoord.GetDistanceTo(eCoord);

But, it seems like the GeoCoordinate class is not supported in .NET core. Is there any other precise way to calculate the distance between 2 coordinates using the latitude and longitude in .NET core?

Kezia Rose
  • 365
  • 1
  • 2
  • 12

1 Answers1

22

GeoCoordinate class is part of System.Device.dll in .net framework. But, it is not supported in .Net Core. I have found alternative methods to find the distance between 2 coordinates.

    public double CalculateDistance(Location point1, Location point2)
    {
        var d1 = point1.Latitude * (Math.PI / 180.0);
        var num1 = point1.Longitude * (Math.PI / 180.0);
        var d2 = point2.Latitude * (Math.PI / 180.0);
        var num2 = point2.Longitude * (Math.PI / 180.0) - num1;
        var d3 = Math.Pow(Math.Sin((d2 - d1) / 2.0), 2.0) +
                 Math.Cos(d1) * Math.Cos(d2) * Math.Pow(Math.Sin(num2 / 2.0), 2.0);
        return 6376500.0 * (2.0 * Math.Atan2(Math.Sqrt(d3), Math.Sqrt(1.0 - d3)));
    }

where point1 and point2 are 2 points with the coordinates and Location is a class as shown below,

public class Location
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

Please check the link for another method to calculate the distance, which gives the same result as the above code - Alternative method

Community
  • 1
  • 1
Kezia Rose
  • 365
  • 1
  • 2
  • 12
  • 6
    For reference, the above method returns the distance in meters. Also, if you're able to leverage multi-targeting in your project, Microsoft has a .Net Core GeoLocation NuGet package: https://www.nuget.org/packages/Geolocation.NetStandard/ – Andy Stagg Sep 23 '20 at 16:57
  • 1
    Thank you for this simple answer. Seems other solutions involve complicated projections. This was easy to use. – Heems Aug 19 '21 at 00:24
  • In 2022, this original Geolocation nuget package seems to be compatible with .NET core - https://www.nuget.org/packages/Geolocation/ – Kunal Apr 22 '22 at 15:55
  • 5
    Is this really a Nuget published by Microsoft? I see an individual's name as the author. I would love to see Microsoft itself publish one – jglouie May 29 '22 at 21:51
  • As an alternative to the other libraries recommended, you can use https://www.nuget.org/packages/GeoCoordinate.NetCore as a .Net Core replacement for the .Net framework GeoCoordinate. – Popa Andrei Mar 14 '23 at 14:22