I want to develop an android app which can calculate the actual distance traveled and show it in a text view. Here is the code I used but this code decreases the traveled distance when you heading back to the start point. Can anyone help to fix this code so it can accumulate distances only?
display = (TextView) findViewById(R.id.info);
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0,0, Loclist);
loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
if (loc == null) {
display.setText("No GPS location found");
} else {
//set Current latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
}
//Set the last latitude and longitude
lastLat = currentLat;
lastLon = currentLon;
}
LocationListener Loclist = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
//set Current latitude and longitude
currentLon=loc.getLongitude();
currentLat=loc.getLatitude();
// TODO Auto-generated method stub
//start location manager
LocationManager lm =(LocationManager) getSystemService(LOCATION_SERVICE);
//Get last location
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
//Request new location
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0,0, Loclist);
//Get new location
Location loc2 = lm.getLastKnownLocation(lm.GPS_PROVIDER);
//get the current lat and long
currentLat = loc.getLatitude();
currentLon = loc.getLongitude();
Location locationA = new Location("point A");
locationA.setLatitude(lastLat);
locationA.setLongitude(lastLon);
Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);
double distanceMeters = locationA.distanceTo(locationB);
double distanceKm = distanceMeters / 1000f;
display.setText(String.format("%.2f Km",distanceKm ));
Location locationC = new Location("point c");
locationA.setLatitude(currentLat);
locationA.setLongitude(currentLon);
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Thanks in advance.