C# - Calculate distance between GPS coordinates

By , 12/28/2012
(1 ratings)
This snippets allows to calculate the distance between two or more GPS coordinates using the Great Circle Distance-algorithm (http://en.wikipedia.org/wiki/Great-circle_distance).

You get back a Double value (measured in kilometers).

Example:
Beeline between
Mannheim -> Ludwigshafen -> Stuttgart -> Berlin

double distance =
TrackingHelper.CalculateDistance(
new Location() { Latitude = 49.4833270, Longitude = 8.4748935 },
new Location() { Latitude = 49.4822117, Longitude = 8.4378147 },
new Location() { Latitude = 48.7794059, Longitude = 9.1755294 },
new Location() { Latitude = 52.5230417, Longitude = 13.4108447 });


Author: Marcell Spies, translation by Michael List
public class Location
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

public static class TrackingHelper
{
    private static double DegreesToRadians(double degrees)
    {
        return degrees * Math.PI / 180.0;
    }

    public static double CalculateDistance(Location location1, Location location2)
    {
        double circumference = 40000.0; // Earth's circumference at the equator in km
        double distance = 0.0;
        
        //Calculate radians
        double latitude1Rad = DegreesToRadians(location1.Latitude);
        double longitude1Rad = DegreesToRadians(location1.Longitude);
        double latititude2Rad = DegreesToRadians(location2.Latitude);
        double longitude2Rad = DegreesToRadians(location2.Longitude);

        double logitudeDiff = Math.Abs(longitude1Rad - longitude2Rad);

        if (logitudeDiff > Math.PI)
        {
            logitudeDiff = 2.0 * Math.PI - logitudeDiff;
        }
        
        double angleCalculation =
            Math.Acos(
              Math.Sin(latititude2Rad) * Math.Sin(latitude1Rad) +
              Math.Cos(latititude2Rad) * Math.Cos(latitude1Rad) * Math.Cos(logitudeDiff));

        distance = circumference * angleCalculation / (2.0 * Math.PI);

        return distance;
    }

    public static double CalculateDistance(params Location[] locations)
    {
        double totalDistance = 0.0;

        for (int i = 0; i < locations.Length - 1; i++)
        {
            Location current = locations[i];
            Location next = locations[i + 1];

            totalDistance += CalculateDistance(current, next);
        }

        return totalDistance;
    }
}

1 Comments

By lanjos, 7/4/2013
Thanks you, i have tried a lot calculator and all of them was given wrong result. but yours is the way to go. thank you for sharing.

God bless you...
 

Log in, to comment!