2012-10-15 233 views
1

可能重複:
Android : Location.distanceTo not working correctly?計算距離

我試圖以計算用戶位置之間(駕駛員或移動位置)與一個固定的緯度距離經度。但是,文本不會顯示結果並只顯示TextView。

而且每當用戶到達固定緯度經度的某個半徑時,imageview將變爲另一個drawable。我一直試圖這樣做了一個多星期。任何幫助傢伙?


主要代碼:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.lights); 


    //placing location 
    LocationManager loc = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    Location location = loc.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
    double clong = location.getLongitude(); 
    double clat = location.getLatitude(); //current longitude and latitude 

    double latitude=0.305085; 
    double longitude=101.70506;  //fixed location 

    double dist = Math.sqrt(Math.pow((111.3 * (latitude - clat)),2) + Math.pow((71.5 * (longitude - clong)),2)) * 1000; 


if(dist<1000){ 
    calculate(dist); 

    tvDis = (TextView)findViewById(R.id.distance); 

    tvDis.setText(dist+"m"); 

} 

} 



public void calculate(double x){ 
    ImageView light = (ImageView)findViewById(R.id.imageView1); 

    if (x<1000){ 

     light.setImageResource(R.drawable.icon_yellow); 

     if(x<500){ 
      light.setImageResource(R.drawable.icon_red); 
     } 
    } 
    else{ 
     light.setImageResource(R.drawable.icon_green); 
    } 

} 

我試圖改變1000爲更大的數字,但仍然沒有運氣。

+0

你可以嘗試做一些關於這個問題的研究。查看上面的問題以獲得兩個地點之間的距離。 –

+0

@MarvinLabs我確實試圖找到任何讓我的生活更容易編碼的東西。這就是我想出這個代碼的原因。請你能告訴我我做錯了什麼嗎? – akemalFirdaus

+0

只需閱讀Location類的文檔,即可計算兩點之間的距離。見下面的答案。 –

回答

2

從開發者網站

public static void distanceBetween (double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results) 

http://developer.android.com/reference/android/location/Location.html

+2

如果您已經準備好兩個位置對象,您還可以添加:'public float distanceTo(Location dest)'。 –

+0

@MarvinLabs我試圖使用這種方法,但返回的float []結果中的值是負數。我不確定這是什麼意思,它在公里,米或英里? – akemalFirdaus

+0

RTFM,它明確寫在那裏。 –