Search code examples
javagoogle-mapsgoogle-apigoogle-api-client

How to get the time of public transport in maps api


I am building a personal project to familiarise myself with API calling etc.

I have the following function:

    public void calculateDistance(House house) {

    DirectionsApiRequest apiRequest = DirectionsApi.newRequest(geoApiContext);
    apiRequest.origin(new LatLng(house.getLat(), house.getLon()));
    apiRequest.destination(biminghamInternationStationLonLat);
    apiRequest.mode(TravelMode.TRANSIT);
    apiRequest.setCallback(new com.google.maps.PendingResult.Callback<DirectionsResult>() {
        @Override
        public void onResult(DirectionsResult result) {
            DirectionsRoute[] routes = result.routes;
            System.out.println("Printing out the results for " + house.getUrlListing());

            for(int i =0 ; i < routes.length; i++)
            {
                DirectionsRoute route = routes[i];
                System.out.println(route);
            }
        }

        @Override
        public void onFailure(Throwable e) {

        }
    });
}

What this function does is gets the latitude and longitude of the custom House object I am providing, and essentially finds how long it takes to reach birmingham international station via public transport (hence the TRANSIT mode in the apiRequest).

But I'm not sure if I am using it correctly? When I go on google maps website and check how long it'll take for me to get to birmingham international station from the location of the house; I get results varying from 30-35 mins, okay. But when I try calling the above code it prints the following:

[DirectionsRoute: "", 1 legs, waypointOrder=[], bounds=[52.48039080,-1.72493200, 52.45082300,-1.78392750], 1 warnings]

I'm not sure how I can get the time it takes via public transport from the api. I am using the Directions API.. not sure if im using the wrong API but when looking at what API to use, this was described what I needed..


Solution

  • I can see that you are using the Java Client for Google Maps Services. In order to understand how to work with the library I can suggest having a look at the JavaDoc that located at

    https://www.javadoc.io/doc/com.google.maps/google-maps-services/latest/index.html

    Checking the JavaDoc documentation you will see that DirectionsRoute object contains an array of DirectionsLeg[] and the direction leg in its turn has a field with Duration object. So you need to loop through all legs of the route and sum up leg's duration that will give you a complete route duration in seconds.

    Referring to the synchronous calls in the Java client library, you can do requests synchronously calling the await() method of the request.

    Have a look at the following example that is based on your code. It shows how to get transit directions synchronously and calculate the duration in seconds for the first route

    import com.google.maps.GeoApiContext;
    import com.google.maps.DirectionsApiRequest;
    import com.google.maps.DirectionsApi;
    import com.google.maps.model.DirectionsResult;
    import com.google.maps.model.DirectionsRoute;
    import com.google.maps.model.DirectionsLeg;
    import com.google.maps.model.LatLng;
    import com.google.maps.model.TravelMode;
    
    
    class Main {
      public static void main(String[] args) {
        GeoApiContext context = new GeoApiContext.Builder()
        .apiKey("YOUR_API_KEY")
        .build();
    
        DirectionsApiRequest apiRequest = DirectionsApi.newRequest(context);
        apiRequest.origin(new LatLng(41.385064,2.173403));
        apiRequest.destination(new LatLng(40.416775,-3.70379));
        apiRequest.mode(TravelMode.TRANSIT);
    
        long duration = 0;
      
        try {
          DirectionsResult res = apiRequest.await();
    
          //Loop through legs of first route and get duration
          if (res.routes != null && res.routes.length > 0) {
              DirectionsRoute route = res.routes[0];
    
              if (route.legs !=null) {
                  for(int i=0; i<route.legs.length; i++) {
                      DirectionsLeg leg = route.legs[i];
                      duration += leg.duration.inSeconds;
                  }    
              }
          }
        } catch(Exception ex) {
          System.out.println(ex.getMessage());
        }
    
        System.out.println("Duration (sec): " + duration);
      }
    } 
    

    Enjoy!