Skip to content

Instantly share code, notes, and snippets.

@ElliotWood
Last active December 15, 2015 12:28
Show Gist options
  • Save ElliotWood/5260034 to your computer and use it in GitHub Desktop.
Save ElliotWood/5260034 to your computer and use it in GitHub Desktop.
Calculating Distance between two Latitude and Longitude GeoCoordinates
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;
}
var sCoord = new GeoCoordinate(sLatitude, sLongitude);
var eCoord = new GeoCoordinate(eLatitude, eLongitude);
return sCoord.DistanceTo(eCoord);
function distanceTo(lat1, lon1, lat2, lon2, unit) {
var rlat1 = Math.PI * lat1/180
var rlat2 = Math.PI * lat2/180
var rlon1 = Math.PI * lon1/180
var rlon2 = Math.PI * lon2/180
var theta = lon1-lon2
var rtheta = Math.PI * theta/180
var dist = Math.sin(rlat1) * Math.sin(rlat2) + Math.cos(rlat1) * Math.cos(rlat2) * Math.cos(rtheta);
dist = Math.acos(dist)
dist = dist * 180/Math.PI
dist = dist * 60 * 1.1515
if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }
return dist
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment