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 radiansOverDegrees = (Math.PI / 180.0);
var sLatitudeRadians = sLatitude * radiansOverDegrees;
var sLongitudeRadians = sLongitude * radiansOverDegrees;
var eLatitudeRadians = eLatitude * radiansOverDegrees;
var eLongitudeRadians = eLongitude * radiansOverDegrees;
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?
The GeoCoordinate class (.NET Framework 4 and higher) already has
GetDistanceTo
method.The distance is in meters.
You need to reference System.Device.
You can use this function :
Source : https://www.geodatasource.com/developers/c-sharp
GetDistance is the best solution, but in many cases we can't use this Method (e.g. Universal App)
Pseudocode of the Algorithm to calculate the distance between to coorindates:
Real World C# Implementation, which makes use of an Extension Methods
Usage:
Implementation:
Here is the JavaScript version guys and gals
And here, for those still not satisfied, the original code from .NET-Frameworks
GeoCoordinate
class, refactored into a standalone method:Earth mean radius = 6,371km = 3958.76 miles
Rather than use
var
I suggest you usedouble
, just to be explicit.