2

I need to find the distance(Km) between 2 points in windows 8.1 apps using c# so i used the function below, but the returned value not correct any help please:

public static double DistanceTo(Double latitude1, Double longitude1, Double latitude2, Double longitude2)
    {
        var a = latitude1 - latitude2;
        var b = longitude1 - longitude2;

        return Math.Sqrt(a * a + b * b);
    }
leppie
  • 109,129
  • 16
  • 185
  • 292
ahmad
  • 93
  • 2
  • 12

2 Answers2

7

You use the wrong formula. That's the reason you don't get the correct result. The formula you use is the one we use for the calculation of the distance between two points in the same plane and can be proved using the pythagora's theorem. However when we want to calculate the distance between two point on the surface of a sphere (we assume that the earth is a perfect sphere), we don't use this type.

Here is a link with the correct formula and an implementation in JavaScript.

Below, I have an implementation in C#

At first we have to define a method that would take as a parameter an angle and it will return it's value in radians.

public double ConvertToRadians(double angle)
{
    return (Math.PI / 180) * angle;
}

Then we could define our method for the calculation of the distance:

public static double DistanceTo(double latitude1, 
                                double longitude1, 
                                double latitude2, 
                                double longitude2)
{
    // The radius of the earth in Km.
    // You could also use a better estimation of the radius of the earth
    // using decimals digits, but you have to change then the int to double.
    int R = 6371; 

    double f1 = ConvertToRadians(latitude1);
    double f2 = ConvertToRadians(latitude2);

    double df = ConvertToRadians(latitude1-latitude2);
    double dl = ConvertToRadians(longitude1-longitude2);

    double a = Math.Sin(dφ/2) * Math.Sin(dφ/2) +
    Math.Cos(f1) * Math.Cos(f2) *
    Math.Sin(dλ/2) * Math.Sin(dλ/2);

    double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1-a));

    // Calculate the distance.
    double d = R * c;

    return d; 
}

If you don't want to implement it as above, you could use the GeoCoordinate class, which

Represents a geographical location that is determined by latitude and longitude coordinates. May also include altitude, accuracy, speed, and course information.

If you do so, then:

var point1 = new GeoCoordinate(latitude1, longitude1);
var point2 = new GeoCoordinate(latitude2, latitude2);

and then you get the distance between point1 and point2 like below:

point1.GetDistanceTo(point2);
Christos
  • 50,311
  • 8
  • 62
  • 97
1

Try something like this:

var coord1 = new GeoCoordinate(lat1, long1);
var coord2 = new GeoCoordinate(lat2, long2);

var distance = coord1.GetDistanceTo(coord2);

Look here. Seems like a duplicate

Community
  • 1
  • 1
bit
  • 4,139
  • 1
  • 25
  • 44