即時通訊使用經緯度/ lng來查找我的用戶在哪裏,並計算他和地圖中另一個地方之間的距離(其lat/lng是靜態的)。爲了做到這一點,我使用:刷新經緯度或加載更快
private void findloc() {
// TODO Auto-generated method stub
try{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Double lat = Double.valueOf(location.getLatitude());
Double lng = Double.valueOf(location.getLongitude());
Location location2 = new Location("gps");
location2.setLatitude(35.519583);
location2.setLongitude(24.016864);
float distance = location2.distanceTo(location);
TextView sitesdistancekm = (TextView) findViewById(R.id.sitesdistancekm);
sitesdistancekm.setText("Geographical Distance : "+distance/1000+" km");
Toast.makeText(otto.this, "lat: "+lat+"\nlng: "+lng,
Toast.LENGTH_LONG).show();
}
catch(Exception e){
TextView sitesdistancekm = (TextView) findViewById(R.id.sitesdistancekm);
sitesdistancekm.setText("No GPS signal");
}
}
我的問題是,有時位置堆棧和即時得到一個錯誤的距離.IM調用findloc()作爲菜單的刷新,但它不改變。
public boolean onOptionsItemSelected(MenuItem item) {
findloc();
return true;
}
有什麼辦法可以改進它嗎?
編輯
這樣會行嗎?
private void findloc() {
// TODO Auto-generated method stub
try{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Double lat = Double.valueOf(location.getLatitude());
Double lng = Double.valueOf(location.getLongitude());
location2 = new Location("gps");
location2.setLatitude(35.519583);
location2.setLongitude(24.016864);
float distance = location2.distanceTo(location);
TextView sitesdistancekm = (TextView) findViewById(R.id.sitesdistancekm);
sitesdistancekm.setText("Geographical Distance : "+distance/1000+" km");
Toast.makeText(otto.this, "lat: "+lat+"\nlng: "+lng,
Toast.LENGTH_LONG).show();
onLocationChanged(location);
}
catch(Exception e){
TextView sitesdistancekm = (TextView) findViewById(R.id.sitesdistancekm);
sitesdistancekm.setText("No GPS signal");
}
}
private void onLocationChanged(Location location) {
// TODO Auto-generated method st
float distance = location2.distanceTo(location);
TextView sitesdistancekm = (TextView) findViewById(R.id.sitesdistancekm);
sitesdistancekm.setText("Geographical Distance : "+distance/1000+" km");
}
IIRC,該文件提到之前你提供位置更新的地方,'getLastKnownLocation()'可以返回不準確的結果在某些情況下,例如在一段時間內GPS尚未打開的情況下。 – thegrinner
@jack可能我有一個示例代碼? – kostas
我已經嘗試過它與位置監聽器,但這種方式需要更多的時間來找到我的經緯度/我的使用.... – kostas