Как рассчитать сводку маршрутов

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

  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();
    });