Mohammad Rajob Mohammad Rajob - 24 days ago 6
Android Question

Android GPS: measured distance between locations continiously

I want to create an application of distance tracker in android. I have a

Spinner, button
and a
TextView
.
Initially text view will be 0.00km.
When I click the button (GPS tracking start) and start walking in the text view it will show the distance continuously. When I click the button again(GPS tracking terminate) and show the full distance between clicking button.

Here is the screenshot that the application will look like:

starting app

after click start button

Here is My Code:

public class Gps extends Activity {

TextView display;


double currentLon=0 ;
double currentLat=0 ;
double lastLon = 0;
double lastLat = 0;
double distance;




public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);

display = (TextView) findViewById(R.id.textView1);


LocationManager lm =(LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0,0, Loclist);
Location 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) {
// 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 ));

}



@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



}

};

}


Please help me. Thanks.

Answer

You should register a listener on the GPS when the location changed. You basically have to store the previous known location and compare it with the new one.

The simplest way to get the distance between two points would be to use:

sqrt( (x2 - x1)^2 + (y2 - y1)^2 + (z2 - z1)^2 )
  • X may be the latitude
  • Y may be the longitude
  • Z may be the altitude

Here is a pseudo code sample to help you

public class GpsCalculator
{

    private LocationManager locationManager = null;
    private Location previousLocation = null;
    private double totalDistance = 0D;

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 100; // 100 meters
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minutes

    public void run(Context context)
    {
        // Get the location manager
        locationManager = (LocationManager) context.getSystemService(Service.LOCATION_SERVICE);

        // Add new listeners with the given params
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener); // Network location
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener); // Gps location
    }

    public void stop()
    {
        locationManager.removeUpdates(locationListener);
    }

    private LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location newLocation)
        {
            if (previousLocation != null)
            {
                double latitude = newLocation.getLatitude() + previousLocation.getLatitude();
                latitude *= latitude;
                double longitude = newLocation.getLongitude() + previousLocation.getLongitude();
                longitude *= longitude;
                double altitude = newLocation.getAltitude() + previousLocation.getAltitude();
                altitude *= altitude;
                GpsCalculator.this.totalDistance += Math.sqrt(latitude + longitude + altitude);
            }

            // Update stored location
            GpsCalculator.this.previousLocation = newLocation;
        }

        @Override
        public void onProviderDisabled(String provider) {}

        @Override
        public void onProviderEnabled(String provider) {}

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };
}

And the Activty should look like that:

public class MainActivity extends Activity
{
    private Button mainButton = null;
    private boolean isButtonPressed = false;

    private GpsCalculator gpsCalculator = null;

    public void onCreate(Bundle savedInstance)
    {
        super.onCreate(savedInstance);

        // Create a new GpsCalculator instance
        this.gpsCalculator =  new GpsCalculator();

        // Get your layout + buttons

        this.mainButton = (Button) findViewById(R.id.main_button);

        this.mainButton.addOnClickListener(new OnClickListener() {
            @Override
            public void onClick()
            {
                // Enable or diable gps
                if (MainActivity.this.isButtonPressed) gpsCalculator.run(this);
                else gpsCalculator.stop();

                // Change button state
                MainActivity.this.isButtonPressed = !MainActivity.this.isButtonPressed;
            }
        });
    }
}