Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find distance between 2 coordinates in .NET core

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?

like image 940
Kezia Rose Avatar asked Mar 16 '20 05:03

Kezia Rose


1 Answers

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

like image 137
Kezia Rose Avatar answered Sep 20 '22 22:09

Kezia Rose