2014-10-02 119 views
-1

我需要找到在Windows 8.1的應用程序使用C#,所以我用下面的函數2點之間的距離(公里),但返回的值不正確的任何幫助,請:如何計算2之間的距離座標

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); 
    } 
+2

該公式給出了兩點之間的位移而不是距離。 – bit 2014-10-02 08:43:32

+0

@bit這個公式並沒有給你任何有用的東西。 – DavidG 2014-10-02 08:44:46

+0

有沒有給我距離的公式? – ahmad 2014-10-02 08:44:48

回答

3

您使用了錯誤的公式。這就是你沒有得到正確結果的原因。 您使用的公式是我們用於計算同一平面上兩個點之間的距離 的公式,可以使用畢達哥拉定理來證明。然而,當我們想要計算球體表面上兩點之間的距離(我們假設地球是一個完美的球體)時,我們不使用這種類型。

Here是一個帶有正確公式和JavaScript實現的鏈接。

下面,我在C#

的實現首先,我們要確定,將採取作爲參數的角度的方法,它會返回它的弧度值。

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

然後我們可以定義我們的方法對距離的計算:

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; 
} 

如果你不想實現它如上,你可以使用GeoCoordinate類,它

表示由緯度和經度座標確定的地理位置。還可能包括高度,準確度,速度和 課程信息。

如果這樣做,那麼:

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

,然後你會得到像下面point1point2之間的距離:

point1.GetDistanceTo(point2); 
+0

這是一個很好的解釋。您應該將其添加到原始問題以及:http://stackoverflow.com/q/6366408/1224069 – 2014-10-02 10:47:55

+0

@PhilipPittle非常感謝你的傢伙。 – Christos 2014-10-02 10:49:49

1

嘗試是這樣的:

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

var distance = coord1.GetDistanceTo(coord2); 

Look here。似乎是重複的

相關問題