1

Possible Duplicate:
Android : Location.distanceTo not working correctly?

I am trying to calculate the distance between the user location(driver or moving location) and a fixed latitude longitude. But however the text does not display the result and just displays TextView.

And whenever the user comes to a certain radius of the fixed latitude longitude the imageview will change to another drawable.I have been trying to do this for over a week now. Any help guys?


Main code:

 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);
    }

}

I have tried changing 1000 to a larger number but still there is no luck.

Community
  • 1
  • 1
akemalFirdaus
  • 606
  • 1
  • 7
  • 15
  • You could have tried to do some research on the subject. See above question to get distance between two locations. – Vincent Mimoun-Prat Oct 15 '12 at 17:31
  • @MarvinLabs I did try to find anything that will make my life easier coding this. And that was how I came up with this code. Please can you tell me what I did wrong? – akemalFirdaus Oct 15 '12 at 17:39
  • Simply reading the documentation of the Location class gives you the way to calculate a distance between two points. See answer below. – Vincent Mimoun-Prat Oct 15 '12 at 17:42

1 Answers1

2

From the developers site

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

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

Archie.bpgc
  • 23,812
  • 38
  • 150
  • 226