计算当前位置和点之间的距离

时间:2012-10-15 17:26:50

标签: android gps location distance latitude-longitude

  

可能重复:
  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更改为更大的数字,但仍然没有运气。

1 个答案:

答案 0 :(得分:2)

来自开发者网站

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

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