kian5749
kian5749

Reputation: 65

Geographic coordinate distance calculation with haversine formula gives the wrong output

I'm creating a distance calculator in c# using the haversine equation to calculate the distance between longitudes and latitudes but it is giving the wrong output can anyone see why? the first long and lat values are for a place in Wales (Bangor) and the other is for a place in England (Manchester) Here is the code:

using System;

public static class Program
{
    static double toRadians(double angle)
    {
        return (angle * Math.PI) / 180;
    }

    static double CalcDistance(double lon1, double lon2, double lat1, double lat2)
    {
        lon1 = toRadians(lon1);
        lon2 = toRadians(lon2);
        lat1 = toRadians(lat1);
        lat2 = toRadians(lat2);
        //haversine formula
        double dlat, dlon;
        dlat = lat2 - lat1;
        dlon = lon2 - lon1;
        double a = Math.Pow(Math.Sin(dlat / 2), 2) *
            Math.Cos(lat1) * Math.Cos(lat2) *
            Math.Pow(Math.Sin(dlon / 2), 2);
        double c = 2 * Math.Asin(Math.Sqrt(a));
        // earths radius is KM, use 3956 for miles
        double earthRadius = 6371;
        return (c * earthRadius);
    }



    static void Main(String[] args)
    {
        double lat1, lat2, lon1, lon2;
        lon1= 53.222469;
        lat1 = -4.129424;
        lon2 = 53.244697;
        lat2 = -2.13195;
        Console.WriteLine(CalcDistance(lon1, lon2, lat1, lat2) + " KM");
    }
}

The output given is 0.04301075336978381 KM when the output should be roughly 130KM

Upvotes: 3

Views: 612

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062492

The error is a * vs + (the first one in CalcDistance), but here's a direct conversion from https://www.movable-type.co.uk/scripts/latlong.html, for reference (also adding this to the static double toRadians(this double angle) so it works as an extension method):

static double CalcDistance(double lon1, double lon2, double lat1, double lat2)
{
    const double R = 6371;
    var φ1 = lat1.toRadians();
    var φ2 = lat2.toRadians();
    var Δφ = (lat2 - lat1).toRadians();
    var Δλ = (lon2 - lon1).toRadians();

    var a = Math.Sin(Δφ / 2) * Math.Sin(Δφ / 2) +
            Math.Cos(φ1) * Math.Cos(φ2) *
            Math.Sin(Δλ / 2) * Math.Sin(Δλ / 2);
    var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

    var d = R * c;
    return d;
}

Upvotes: 6

Related Questions