2012-01-12 49 views
10

我想通過latlng獲得從A到B的距離。當我使用下面的代碼運行我的應用程序時,它返回錯誤的結果。 我試了A(31.172740,115.0081630),然後B(30.6055980,114.3603140),結果是3111km左右,但是右邊的距離大概是134km。 我的代碼是:如何通過latlng獲得兩點之間的距離?

class btnListener implements OnClickListener{ 

    public void onClick(View v) { 
     lat_a=lat_A.getText().toString(); 
     lng_a=lng_A.getText().toString(); 
     lat_b=lat_B.getText().toString(); 
     lng_b=lng_B.getText().toString(); 
     double a1,n1,a2,n2; 
     a1=30.6055980; 
     a2=Double.parseDouble(lat_b); 
     n2=Double.parseDouble(lng_b); 
     double R=6371; 
     double D=Math.acos(Math.sin(a1)*Math.sin(a2)+Math.cos(a1)*Math.cos(a2)*Math.cos(n2-n1)); 
     Toast.makeText(getApplication(), "the distance is"+String.valueOf(D*R)+"km from A to B", Toast.LENGTH_SHORT).show(); 
    } 

} 
+0

看看 http://stackoverflow.com/questions/2741403/get-the-distance-between-two-geo-points – Saasha 2012-01-12 08:46:29

+0

許多thanks.i我發現它。 – lanyimo 2012-01-12 08:58:07

回答

12

請嘗試以下代碼。

public float distance (float lat_a, float lng_a, float lat_b, float lng_b) 
{ 
    double earthRadius = 3958.75; 
    double latDiff = Math.toRadians(lat_b-lat_a); 
    double lngDiff = Math.toRadians(lng_b-lng_a); 
    double a = Math.sin(latDiff /2) * Math.sin(latDiff /2) + 
    Math.cos(Math.toRadians(lat_a)) * Math.cos(Math.toRadians(lat_b)) * 
    Math.sin(lngDiff /2) * Math.sin(lngDiff /2); 
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    double distance = earthRadius * c; 

    int meterConversion = 1609; 

    return new Float(distance * meterConversion).floatValue(); 
} 

如果你不明白,please check this link,相同的代碼在這裏可用。

+0

謝謝。讓我們嘗試一下。 – lanyimo 2012-01-12 08:57:18

50

有由Android本身提供了兩個點之間的距離獲得的API。使用:

Location.distanceBetween(
    startLatitude, 
    startLongitude, 
    endLatitude, 
    endLongitude, 
    results); 

它以米爲單位返回距離。

+0

我發現結果是與一種浮動arry。我再試一次。謝謝。 – lanyimo 2012-01-12 08:49:24

+10

值得一提的是,以米爲單位的距離存儲在結果[0]中。更多信息:http://developer.android.com/reference/android/location/Location.html#distanceBetween(double,%20double,%20double,%20double,%20float []) – cyborg86pl 2014-10-09 22:40:28

+1

計算出的距離存儲在結果[ 0]。如果結果長度大於或等於2,則初始方位將存儲在結果[1]中。如果結果長度爲3或更大,則最終方位將存儲在結果[2]中。 – 2017-10-31 15:35:23

相關問題