viclog book
viclog book

Reputation: 11

Android GPS distance Calculation

I am trying to calculate the distance between multiple GPS destinations.

My Approach

I am using Google's Matrix API for this, but it allows at max. 25 points. And I need to track the complete distance travelled by a user.

Any suggestion will be very helpful.

Upvotes: 1

Views: 1812

Answers (2)

athira09
athira09

Reputation: 155

I know this is too late but this is for users who are still searching for a solution.

float[] distanceResults = new float[1];
Location.distanceBetween(oldPosition.latitude, oldPosition.longitude,
        newPosition.latitude, newPosition.longitude, distanceResults);

As per documentation, the above function computes the approximate distance in meters between two locations, and optionally the initial and final bearings of the shortest path between them. Hence, the variable distanceResults will have the distance in meters.

Upvotes: 0

Shane Duffy
Shane Duffy

Reputation: 1147

Using Android SDK:

Try using the Location object's distanceTo function like so:

float getTripDistance(List<LatLng> vertices) {
    float totalDistance = 0;

    for (int i = 0; i < vertices.size() - 1; i++) {
        Location tLoc1 = new Location("");
        Location tLoc2 = new Location("");

        tLoc1.setLatitude(vertices.get(i).latitude);
        tLoc1.setLongitude(vertices.get(i).longitude);

        tLoc2.setLatitude(vertices.get(i + 1).latitude);
        tLoc2.setLongitude(vertices.get(i + 1).longitude);

        totalDistance += tLoc1.distanceTo(tLoc2);
    }

    return totalDistance;
}

You can loop over all of your points sequentially and sum each respective distance in meters to get the total trip distance.

Upvotes: 1

Related Questions