Daniel Prado
Daniel Prado

Reputation: 79

Calculate distance travelled in real time

I want to get the distance in real time, I've found out a lot of posts on internet about it, but so far i haven't been able to make it work, and I'm not sure which is the best option. I also want to display the distance in a TextView. And I'd like to know if I have to use "distanceTo" or "distancebetween"

So far this is what I have, I was following this but I got confused! How to use android distanceBetween() method

LocationManager locationManager = (LocationManager) this
            .getSystemService(Context.LOCATION_SERVICE);

    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {

            Location oldLoc=0, newLoc=0;

            location.getLatitude();
            location.getLongitude();

            if(oldLoc!=null){
                if(newLoc == null){
                    newLoc = location;

                }
            }

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

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
        }
    };

Upvotes: 0

Views: 173

Answers (1)

Daniel Nugent
Daniel Nugent

Reputation: 43322

Just increment the distance travelled each time a new Location comes in.

Use member variables to store the previous location, the distance travelled so far, and a reference to the TextView you want to update:

Location mPrevLocation = null;
float mDistanceTravelled = 0.0F;
TextView mDistanceTextView;

Then, use this code to keep track of the distance, and update the TextView:

LocationListener locationListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        if (mPrevLocation != null) {
            mDistanceTravelled += mPrevLocation.distanceTo(location);
            mDistanceTextView.setText(String.valueOf(mDistanceTravelled));
        }
        mPrevLocation = location;
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {}

    @Override
    public void onProviderEnabled(String provider) {}

    @Override
    public void onProviderDisabled(String provider) {}
};

Upvotes: 1

Related Questions