Kyaw Myint Cho
Kyaw Myint Cho

Reputation: 11

How to find previous Location in android to measure how far I travel

How to get previous Location in Android? I am trying to make an app that will update a location every 30 seconds and I want to measure how much I travel by finding distance between previous location and current location. However, I was only able to get current location. Here is my code

public void onCreate(Bundle savedInstanceState)
{   //This is for the UI
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    showData = (TextView)findViewById(R.id.showText);
    start = (Button)findViewById(R.id.startButton);
    stop = (Button)findViewById(R.id.stopButton);

    start.setOnClickListener(globalListener);
    stop.setOnClickListener(globalListener);
   //This is for the Location
   locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER,10,10,this);
}
public void onLocationChanged(Location location)
{

    distance = location.distanceTo(previousLocation);
    meter = distance + meter;
    showData.setText(Double.toString(meter));
}

public void onStatusChanged(String provider, int status, Bundle extras) {
    //To change body of implemented methods use File | Settings | File Templates.
}

public void onProviderEnabled(String provider) {
    //To change body of implemented methods use File | Settings | File Templates.
}

public void onProviderDisabled(String provider) {
    //To change body of implemented methods use File | Settings | File Templates.
}

Upvotes: 0

Views: 248

Answers (2)

Srikant Sahay
Srikant Sahay

Reputation: 985

Android System keeps only stores the last location that it gets. It doesn't store any previous location. You'll have to implement that on your own. Every time you get a location update, save the location. The next time you request and get a new location, you will have the old location to compare it with.

Upvotes: 0

Marek
Marek

Reputation: 4081

Why won't you store the current location and then after 30 seconds read this stored value.
By doing this you can subtract it from new value and get the result which you are looking for.

Define two variables

Location oldLocation;
Location newLocation;

And then you can do in a loop something like this:

oldLocation = newLocation;
newLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//Here you can start calculating

Make sure you will set newLocation before entering the loop.

It is what you were looking for?

Upvotes: 2

Related Questions