See Yah Later
See Yah Later

Reputation: 97

Compute Latitude and Longitude to Kilometer

I'm trying to calculate my Kilometer distance from my Destination1 to Destination2 using latitude and longitude

Destination1(Cebu City PH) has Latitude: 1017.8590 and Longitude: 12353.4304

Destination2(Talisay PH) has Latitude: 1015.6445 and Longitude: 12350.0404

My output is: 299.28607720457882 KM

CODE:

double lat1 = Convert.ToDouble(txtLat1.Text.ToString());
double lat2 = Convert.ToDouble(txtLat2.Text.ToString());
double lon1 = Convert.ToDouble(txtLong1.Text.ToString());
double lon2 = Convert.ToDouble(txtLong2.Text.ToString());

        var R = 6378.137; // Radius of earth in KM
        var dLat = (lat2 - lat1) * Math.PI / 180;
        var dLon = (lon2 - lon1) * Math.PI / 180;
        var a =
            Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
            Math.Cos(lat1 * Math.PI / 180) * Math.Cos(lat2 * Math.PI / 180) *
            Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
        var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
        string x = (R * c).ToString();
        var d = (R * c);

I try using http://www.entfernungsrechner.net/en/distance/city/1717512/city/1683881 this website to calculate the Kilometer of that Destination and the output is 12.2 km

Upvotes: 0

Views: 509

Answers (1)

Ray Suelzer
Ray Suelzer

Reputation: 4107

Well, for starters it says 12.2KM as you would drive. Which is not going to be the same output as your Haversine formula you have above.

You should try putting the decimals in the right spots. I get a more reasonable result of 4.45 Kilometers.

https://dotnetfiddle.net/cs5Ppq

public class Program
{
    public static void Main()
    {
        double lat1 = 10.178590;
        double lat2 = 10.156445;
        double lon1 = 123.500404;
        double lon2 = 123.534304;

        var R = 6378.137; // Radius of earth in KM
        var dLat = (lat2 - lat1) * Math.PI / 180;
        var dLon = (lon2 - lon1) * Math.PI / 180;
        var a =
            Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
            Math.Cos(lat1 * Math.PI / 180) * Math.Cos(lat2 * Math.PI / 180) *
            Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
        var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
        string x = (R * c).ToString();
        var d = (R * c);
        Console.WriteLine(d);
    }
}

Note: you can check your results against this http://andrew.hedges.name/experiments/haversine/ tool

Edit: If you want the most possibly accurate number, as the Haversine formula can underestimate and overestimate distances at the extremes on the earth, you want to use the Vincety solution. This is not for the weak of heart: http://www.movable-type.co.uk/scripts/latlong-vincenty.html

Upvotes: 1

Related Questions