Search code examples
androidgoogle-mapsgoogle-directions-api

track distance and time based on my track details


I am working on gps tracking in android to track the user location and provide the feature to record the track.I am able to draw path now i want to calculate the track distance and time with that like suppose user start tracking record and move to another location now i want to calculate total distance and time travel for from start to end position (with user location update) in google map. I have function which calculate the distance for 2 position but that not fit for my route, because route are in polyline and it's flexible lat/lng position. is their any api or any function or services provide by google for that. any help or suggestion are appreciate.


Solution

  • I would create a class called waypoint

    class WayPoint
    {
       DateTime depart; //some date time container
       DateTime arrive; //some date time container
       Coordinate position; //some gps coordinate
    }
    

    Then create a list of these classes which allows inserting of elements at any position which is helpful if your route changes:

    List<WayPoint> journey = new ArrayList<WayPoint>();
    
    //just add your waypoints
    
    journey.add(startWayPoint);
    journey.add(wayPoint_1);
    journey.add(wayPoint_2);
    //...
    journey.add(wayPoint_n_minus_2);
    journey.add(wayPoint_n_minus_1);
    journey.add(endWayPoint);
    

    Then convert to array and calculate the totals:

    WayPoint[] wayPoints = journey.toArray();
    
    double total_distance = 0.0f; //distance in metres
    double total_travel_time = 0.0f; // time in hours
    
    //start at index 1 because there are n-1 segments
    if(wayPoints.length>1)
    foreach(int i=1; i<wayPoints.length;i++)
    {
      total_distance += calcDistanceBetween(
          wayPoints[i-1].position,
          wayPoints[i].position);
    
      total_time += calcTimeInHoursBetween(
          wayPoints[i-1].depart,
          wayPoints[i].arrive);
    }
    
    log.d("Total Distance",String.valueOf(total_distance));
    log.d("Total Travel Time",String.valueOf(total_travel_time));