
Here is a quick example:
var location1 = new GeoCoordinates(-29.83245, 31.04034);
var location2 = new GeoCoordinates(-51.39792, -0.12084);
double distance = location1 .GetDistanceTo(location2);
Under the hood
The formulas used in the method is actually using the Haversine method. It assumes that the earth is a perfect sphere rather than an ellipsoid, so as a result, it has an error of less than 0.1 percent.
Since it didn't account for altitude in its calculation, the distance is shorter than the driving distance.
public class GeoCoordinate
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
public class GeoCoordinateTool
{
public double Distance(GeoCoordinate loc1, GeoCoordinate loc2, int type)
{
//1- miles, other km
//Use 3960 if you want miles; use 6371 if you want km
double R = (type == 1) ? 3960 : 6371; // R is earth radius.
double dLat = this.toRadian(loc2.Latitude - loc1.Latitude);
double dLon = this.toRadian(loc2.Longitude - loc1.Longitude);
double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(this.toRadian(loc1.Latitude)) * Math.Cos(this.toRadian(loc2.Latitude)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)));
double d = R * c;
return d;
}
private double toRadian(double val)
{
return (Math.PI / 180) * val;
}
}
How to use this class?
GeoCoordinate g1 = new GeoCoordinate();
GeoCoordinate g2 = new GeoCoordinate();
g1.Latitude =-29.83245;
g1.Longitude = 31.04034;
g2.Latitude = -51.39792;
g2.Longitude = -0.12084;
var geotool = new GeoCoordinateTool();
var distance = geotool.Distance(g1, g2, 1);
- The Haversine Formula (Assume Earth is spherical)
- The Vincenty's Formula (More Accurate;Using Theoretical Ellipsoid for Earth)