Calculating distance between two GPS positions with C#
Posted: (EET/GMT+2)
I'm currently working on a Windows Phone application where I needed to calculate the distance of two latitude/longitude pairs, based on the user's current GPS location. Previously, I've always relied on some backend to do the calculation, so it's good to learn how to calculate this yourself as well.
The below C# implementation shows a method that takes in two lat/long pairs, and returns the distance between these two points in kilometers. If you wanted to get the distance in miles, you can divide the result by 1.609. The formula itself is based on an Excel formula, which is the following:
=ACOS(COS(RADIANS(90-Lat1))*COS(RADIANS(90-Lat2))+SIN(RADIANS(90-Lat1))* SIN(RADIANS(90-Lat2))*COS(RADIANS(Long1-Long2)))*6371
Thanks FC for the Excel link tip.
Here's the C# sample code you've been looking for:
internal static double CalculateDistanceToCurrentLocation(
double lat1, double long1, double lat2, double long2)
{
const double EarthMeanRadius = 6371;
double lat2 = currentLocation.Latitude;
double long2 = currentLocation.Longitude;
double distance = Math.Acos(Math.Cos(DegreesToRadians(90 - lat1)) *
Math.Cos(DegreesToRadians(90 - lat2)) + Math.Sin(DegreesToRadians(90 - lat1)) *
Math.Sin(DegreesToRadians(90 - lat2)) * Math.Cos(DegreesToRadians(long1 - long2))) *
EarthMeanRadius;
// return distance in kilometers
return distance;
}
private static double DegreesToRadians(double degrees)
{
double radians = degrees * (Math.PI / 180);
return radians;
}
Good luck with your own implementations!
Keywords: How to calculate distance between two positions; howto; C# and .NET; distance of two GeoCoordinates.