Search code examples
javajava-streamgoogle-distancematrix-api

Java streams, wait for Google distance matrix to return result


I have a list of vehicles that I need to calculate the total fuel used per vehicle. I am using Java streams to loop through the list, get a vehicle, calculate its distance using the Google distance matrix api, use the distance to calculate fuel usage and return a response. I have noticed that the program just hangs most likely it could be that the stream does not wait for the Matrix api to return a response before it moves to the next item, I say this because I have put system.out.println calls in the Matrix method and some messages do not get printed.

The code that is suppose to calculate total fuel usage

vehicles.stream().map(vehicles ->
                calculateTotalFuelBeingUsedByAllVehicles(vehicle, getDistanceBetweenOriginsAndDestination(
                        new LatLng(vehicle.getOrigin().getLatitude(), vehicle.getOrigin().getLatitude()), new LatLng(vehicle.getDestination().getLatitude(), vehicles.getDestination().getLatitude()))))
                .collect(Collectors.toList());
    public static double getDistanceBetweenOriginsAndDestination(LatLng origin, LatLng destination){
        //Gets printed
        System.out.println("Calculating distance");
        GeoApiContext context = new GeoApiContext.Builder()
                .apiKey(GOOGLE_MAPS_API_KEY)
                .build();
        DistanceMatrixApiRequest distanceMatrixApiRequest = DistanceMatrixApi.newRequest(context)
                .mode(TravelMode.DRIVING)
                .trafficModel(TrafficModel.BEST_GUESS)
                .departureTime(Instant.now().atZone(ZoneOffset.UTC).toInstant())
                .destinations(destination)
                .origins(origin);
        try {

            long distance =  Arrays.stream(distanceMatrixApiRequest.await().rows)
                    .flatMap(distanceMatrixRow -> Arrays.stream(distanceMatrixRow.elements))
                    .mapToLong(distanceMatrixElement -> distanceMatrixElement.distance.inMeters)
                    .sum();

            //Never gets printed
            System.out.println("Calculated distance: "+distance);
            return distance;

        } catch (ApiException | InterruptedException | IOException e) {
            //Never gets printed
            System.out.println("Error encountered when calculating distance");
            e.printStackTrace();
        }
        return 0;
    }

In the getDistanceBetweenOriginsAndDestination the System.out.println("Calculating distance") gets printed and the rest are not.


Solution

  • You have a typo at the creation of LatLng, you send latitude instead of longitude. It may be Google doesn't respond you or takes a lot of time to respond, because it is impossible to calculate a route between these points.