Рассчитать сводку маршрутизации

Чтобы использовать текстовый поиск (новый) или поиск поблизости (новый) для расчета длительности поездки и расстояния до каждого места в ответе:

  1. Передайте параметр RoutingParameters в запросе, используя setOrigin() для указания координат широты и долготы точки начала маршрута. Этот параметр необходим для расчета длительности пути и расстояния до каждого пункта в ответе.

  2. При построении объекта запроса добавьте .setRoutingSummariesIncluded(true) .

В следующем запросе вы рассчитываете длительность поездки и расстояние до каждого места в ответе Text Search (New):

// Specify the list of fields to return.
final List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME);

// Define the routing parameters object and pass the routing origin.
RoutingParameters routingParameters = RoutingParameters.builder()
    .setOrigin(toLatLng("-33.8688, 151.1957362"))
    .build();

// Use the builder to create a SearchByTextRequest object and pass the routing parameters.
// Set setRoutingSummariesIncluded to true.
final SearchByTextRequest searchByTextRequest = SearchByTextRequest.builder("Spicy Vegetarian Food in Sydney, Australia", placeFields)
    .setMaxResultCount(10)
    .setRoutingParameters(routingParameters)
    .setRoutingSummariesIncluded(true)
    .build();

// Call PlacesClient.searchByText() to perform the search.
// Define a response handler to process the returned Lists of Place objects, RoutingSummary objects, and Leg objects.
placesClient.searchByText(searchByTextRequest)   
    .addOnSuccessListener(response -> {
      List<Place> places = response.getPlaces();
      List<RoutingSummary> routingSummaries = response.getRoutingSummaries();
      List<Leg> legs = routingSummaries.get(0).getLegs();
      Duration duration = legs.get(0).getDuration();
    });

Класс SearchByTextResponse представляет ответ на поисковый запрос. Вы можете вызвать метод SearchByTextResponse.getRoutingSummaries() чтобы получить список сводок маршрутизации. Объект SearchByTextResponse также содержит:

  • Список объектов Place , представляющих все соответствующие места, по одному объекту Place на каждое соответствующее место.
  • Каждый объект Place содержит только поля, определенные списком полей, переданным в запросе.

В этом примере вы рассчитываете длительность поездки и расстояние до каждого места в ответе поиска поблизости. В этом примере выполняется поиск ресторанов в Сиднее, Австралия, и для ограничения местоположения и начальной точки маршрута устанавливаются те же координаты широты и долготы:

// Specify the list of fields to return.
final List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME);

// Define the search area as a 500 meter diameter circle in Sydney, Australia.
LatLng center = new LatLng(-33.8688, 151.1957362);
CircularBounds circle = CircularBounds.newInstance(center, /* radius = */ 500);

// Define the routing parameters object and pass the routing origin.
RoutingParameters routingParameters = RoutingParameters.builder()
    .setOrigin(toLatLng("-33.8688, 151.1957362"))
    .build();

// Use the builder to create a SearchNearbyRequest object and pass the routing parameters.
// Set setRoutingSummariesIncluded to true.
final SearchNearbyRequest searchNearbyRequest =
SearchNearbyRequest.builder(/* location restriction = */ circle, placeFields)
    .setIncludedTypes(includedTypes)
    .setMaxResultCount(10)
    .setRoutingParameters(routingParameters)
    .setRoutingSummariesIncluded(true)
    .build();

// Call PlacesClient.searchNearby() to perform the search.
// Define a response handler to process the returned Lists of Place objects, RoutingSummary objects, and Leg objects.
placesClient.searchNearby(searchNearbyRequest)
    .addOnSuccessListener(response -> {
      List<Place> places = response.getPlaces();
      List<RoutingSummary> routingSummaries = response.getRoutingSummaries();
      List<Leg> legs = routingSummaries.get(0).getLegs();
      Duration duration = legs.get(0).getDuration();
    });

Класс SearchNearbyResponse представляет ответ на поисковый запрос. Вы можете вызвать метод SearchNearbyResponse.getRoutingSummaries() чтобы получить список сводок маршрутизации. Объект SearchNearbyResponse также содержит:

  • Список объектов Place , представляющих все соответствующие места, по одному объекту Place на каждое соответствующее место.
  • Каждый объект Place содержит только поля, определенные списком полей, переданным в запросе.

Вам не обязательно использовать одни и те же координаты для ограничения местоположения и для исходной точки маршрута. Например, вы устанавливаете ограничение местоположения по центру Сиднея, чтобы ограничить результаты поиска этим кругом. Но затем вы указываете исходную точку маршрута по координатам вашего дома, то есть по другому месту в пределах круга поиска. После этого запрос ограничивает результаты поиска этим кругом и рассчитывает сводку маршрута на основе местоположения вашего дома.

Укажите варианты поездки

По умолчанию длительность и расстояние рассчитываются для автомобиля. Однако вы можете выбрать тип транспортного средства и другие параметры поиска.

В следующем примере вы указываете режим движения DRIVE и избегаете автомагистралей:

// Specify the list of fields to return.
final List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME);

// Define the routing modifiers object.
RouteModifiers routeModifiers = RouteModifiers.builder()
    .setAvoidHighways(true)
    .build();

// Define the routing parameters object and pass the routing origin.
RoutingParameters routingParameters = RoutingParameters.builder()
    .setOrigin(toLatLng("-33.8688, 151.1957362"))
    .setTravelMode(DRIVE)
    .setRouteModifiers(routeModifiers)
    .build();

// Use the builder to create a SearchByTextRequest object and pass the routing parameters.
// Set setRoutingSummariesIncluded to true.
final SearchByTextRequest searchByTextRequest = SearchByTextRequest.builder("Spicy Vegetarian Food in Sydney, Australia", placeFields)
    .setMaxResultCount(10)
    .setRoutingParameters(routingParameters)
    .setRoutingSummariesIncluded(true)
    .build();

// Call PlacesClient.searchByText() to perform the search.
// Define a response handler to process the returned Lists of Place objects, RoutingSummary objects, and Leg objects.
placesClient.searchByText(searchByTextRequest)   
    .addOnSuccessListener(response -> {
      List<Place> places = response.getPlaces();
      List<RoutingSummary> routingSummaries = result.getRoutingSummaries();
      List<Leg> legs = routingSummaries.get(0).getLegs();
      Duration duration = legs.get(0).getDuration();
    });