2012-11-23 112 views
0

我想通过distanceTo()方法计算android中两个位置(GeoPoint)之间的距离,但是当我运行程序时,方法返回0.0,程序显示0.0KM。为什么?问题是什么?distanceTo()方法返回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()方法B。

Thanks.Cheers

+0

你检查的a和b的值? – Simon

+0

'mylocation'如何初始化?它在哪里宣布? – fiddler

+0

你是否检查过地址确实有经纬度? GeoCoder不保证这一点。 –

回答

0

u能尝试这样

public double distance(float lata, float longa, float latb, float longb) { 
    double d2r = Math.PI/180; 
    double dlong = (longa - longb) * d2r; 
    double dlat = (lata - latb) * d2r; 
    double a = Math.pow(Math.sin(dlat/2.0), 2) + Math.cos(latb * d2r) 
      * Math.cos(lata * d2r) * Math.pow(Math.sin(dlong/2.0), 2); 
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); 
    double d = 6367 * c; 
    return d; 

} 
+0

谢谢,但我想使用distanceTo()方法,我想找到什么问题,并解决这个问题? –