可能重複:
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爲更大的數字,但仍然沒有運氣。
你可以嘗試做一些關於這個問題的研究。查看上面的問題以獲得兩個地點之間的距離。 –
@MarvinLabs我確實試圖找到任何讓我的生活更容易編碼的東西。這就是我想出這個代碼的原因。請你能告訴我我做錯了什麼嗎? – akemalFirdaus
只需閱讀Location類的文檔,即可計算兩點之間的距離。見下面的答案。 –