【发布时间】:2012-11-23 13:27:46
【问题描述】:
我想通过 distanceTo() 方法计算 android 中两个位置 (GeoPoint) 之间的距离,但是当我运行程序时,该方法返回 0.0 并且程序显示 0.0KM。为什么?有什么问题?
public class MyLocation extends MapActivity {
GeoPoint mylocation;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
text_location.setOnKeyListener(new OnKeyListener(){
public boolean onKey(View view, int keyCode,KeyEvent event){
if(keyCode==KeyEvent.KEYCODE_ENTER){
// The map should shows a location that user writes in edittex.
Geocoder geo=new Geocoder(getApplicationContext(),Locale.getDefault());
List<Address> address;
try {
address = geo.getFromLocationName(text_location.getText().toString(),3);
if(address.size()>0){
searchLocation=new GeoPoint((int)(address.get(0).getLatitude()*1e6),(int)(address.get(0).getLongitude()*1e6));
float distance=0;
distance=Distance(searchLocation);
OverlayItem overlayItem=new OverlayIte(searchLocation,textLocation,"Distance:"+distance+"km");
itemizedOverlay.addOverlay(overlayItem); mapOverlays.add(itemizedOverlay);
//
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
return false;
}
});
}
private void initMyLocation() {
final MyLocationOverlay overlay = new MyLocationOverlay(this, map);
overlay.enableMyLocation();
overlay.enableCompass();
//
mylocation=overlay.getMyLocation();
overlay.runOnFirstFix(new Runnable() {
public void run() {
controller.setZoom(13);
controller.animateTo(overlay.getMyLocation());
}
});
}
private float Distance(GeoPoint searchLoc){
Location a=new Location("locA");
Location b=new Location("locB");
if(mylocation!=null){
a.setLatitude(mylocation.getLatitudeE6()/1e6);
a.setLongitude(mylocation.getLongitudeE6()/1e6);
b.setLatitude(searchLoc.getLatitudeE6()/1e6);
b.setLongitude(searchLoc.getLongitudeE6()/1e6);
}
if(a.getLatitude()!=0)
Log.i("this", "is not zero");
else
Log.i("this", "is zero");
float distance=a.distanceTo(b);
return distance;
}
}
我编辑帖子并添加初始化 myLocation 变量的 initMyLocation() 方法,并将日志添加到 Distance() 方法以检查 a 或 b 的值。
谢谢。干杯
【问题讨论】:
-
你检查过a和b的值了吗?
-
mylocation是如何初始化的?它在哪里声明? -
你检查过地址真的有经纬度吗? GeoCoder 不保证这一点。
-
我编辑了第一篇文章。请阅读我的第一篇文章并回答您的问题。登录距离方法显示“这是零”。为什么 a.getLatitude() 是零? MarvinLabs GeoCoder 不保证是什么意思?
-
没人回答我的问题吗?请帮帮我:(