Jason N. Gaylord - 1 month ago 15x

C# Question

I'm calculating the distance between two GeoCoordinates. I'm testing my app against 3-4 other apps. When I'm calculating distance, I tend to get an average of 3.3 miles for my calculation whereas other apps are getting 3.5 miles. It's a big difference for the calculation I'm trying to perform. Are there any good class libraries out there for calculating distance? I'm calculating it like this in C#:

`public static double Calculate(double sLatitude,double sLongitude, double eLatitude,`

double eLongitude)

{

var sLatitudeRadians = sLatitude * (Math.PI / 180.0);

var sLongitudeRadians = sLongitude * (Math.PI / 180.0);

var eLatitudeRadians = eLatitude * (Math.PI / 180.0);

var eLongitudeRadians = eLongitude * (Math.PI / 180.0);

var dLongitude = eLongitudeRadians - sLongitudeRadians;

var dLatitude = eLatitudeRadians - sLatitudeRadians;

var result1 = Math.Pow(Math.Sin(dLatitude / 2.0), 2.0) +

Math.Cos(sLatitudeRadians) * Math.Cos(eLatitudeRadians) *

Math.Pow(Math.Sin(dLongitude / 2.0), 2.0);

// Using 3956 as the number of miles around the earth

var result2 = 3956.0 * 2.0 *

Math.Atan2(Math.Sqrt(result1), Math.Sqrt(1.0 - result1));

return result2;

}

What could I be doing wrong? Should I calculate it in km first and then convert to miles?

Answer

The GeoCoordinate class (.NET Framework 4 and higher) already has `GetDistanceTo`

method.

```
var sCoord = new GeoCoordinate(sLatitude, sLongitude);
var eCoord = new GeoCoordinate(eLatitude, eLongitude);
return sCoord.GetDistanceTo(eCoord);
```

The distance is in meters.

You need to reference System.Device.

Source (Stackoverflow)

Comments