Java流,等待Google距离矩阵返回结果

时间:2019-05-29 07:08:27

标签: java stream google-distancematrix-api

我有一个需要计算每辆车总燃料量的车辆清单。我正在使用Java streams遍历列表,获取车辆,使用Google distance matrix api计算其距离,使用该距离来计算燃料使用量并返回响应。我注意到该程序最有可能挂起,原因可能是stream在移动到下一个项目之前没有等待Matrix api返回响应,我之所以这样说是因为我把{ {1}}中的{1}}呼叫,并且某些消息未打印。

用于计算总燃料使用量的代码

system.out.println
Matrix method

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; } 被打印,其余部分则不被打印。

1 个答案:

答案 0 :(得分:1)

您在创建LatLng时遇到错字,您发送的是纬度而不是经度。 Google可能没有回应您,或花费了很多时间回应,因为无法计算出这些点之间的路线。