2012-10-15 231 views
1

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

+0

你可以尝试做一些关于这个问题的研究。查看上面的问题以获得两个地点之间的距离。 –

+0

@MarvinLabs我确实试图找到任何让我的生活更容易编码的东西。这就是我想出这个代码的原因。请你能告诉我我做错了什么吗? – akemalFirdaus

+0

只需阅读Location类的文档,即可计算两点之间的距离。见下面的答案。 –

回答

2

从开发者网站

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

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

+2

如果您已经准备好两个位置对象,您还可以添加:'public float distanceTo(Location dest)'。 –

+0

@MarvinLabs我试图使用这种方法,但返回的float []结果中的值是负数。我不确定这是什么意思,它在公里,米或英里? – akemalFirdaus

+0

RTFM,它明确写在那里。 –