Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Объедините сводки маршрутизации с поиском по маршруту
Вы можете объединить расчёт сводки маршрута с поиском по маршруту . В этом случае текстовый поиск (новый) возвращает длительность поездки и расстояние до каждого места в ответе, а затем от каждого места до конечного пункта маршрута.
Чтобы использовать текстовый поиск (новый) для расчета сводки маршрута и поиска по маршруту:
Используйте параметр searchAlongRouteParameters.polyline.encodedPolyline , чтобы передать ломаную линию маршрута в функцию Text Search (New), чтобы сместить результаты поиска в соответствии с маршрутом. В ответе будут отображаться места, соответствующие критериям поиска и расположенные рядом с указанным маршрутом.
Добавьте routingSummaries в маску поля, чтобы ответ включал массив routingSummaries . Этот массив содержит длительность и расстояние от начальной точки маршрутизации до каждого места в ответе.
API Explorer позволяет вам делать живые запросы, чтобы вы могли ознакомиться с API и его параметрами:
Ответ содержит два массива: массив places , содержащий соответствующие места, и массив routingSummaries содержащий продолжительность и расстояние поездки до каждого места:
{"places":[{"formattedAddress":"1199 El Camino Real, San Bruno, CA 94066, USA","priceLevel":"PRICE_LEVEL_INEXPENSIVE","displayName":{"text":"Vegan Mob - Vegan BBQ and Soul Food","languageCode":"en"}},{"formattedAddress":"839 Kearny St, San Francisco, CA 94108, USA","priceLevel":"PRICE_LEVEL_MODERATE","displayName":{"text":"Enjoy Vegetarian","languageCode":"en"}},…],"routingSummaries":[{"legs":[{"duration":"285s","distanceMeters":1616},{"duration":"2466s","distanceMeters":58147}],"directionsUri":"https://www.google.com/maps/dir/37.42268,-122.08473/''/37.77877,-122.38781/data=!4m7!4m6!1m0!1m2!1m1!1s0x808f87f9ede375f5:0xa37171fea1a16b28!1m0!3e0"},{"legs":[{"duration":"696s","distanceMeters":4704},{"duration":"2787s","distanceMeters":58901}],"directionsUri":"https://www.google.com/maps/dir/37.42268,-122.08473/''/37.77877,-122.38781/data=!4m7!4m6!1m0!1m2!1m1!1s0x808580f4cebdb06f:0xd3af09e5742234f2!1m0!3e0"},…]}
Для каждой записи в массиве legs текстовый поиск (новый) возвращает время двухэтапной поездки:
Первый этап содержит длительность и расстояние от начальной точки до пункта назначения. В этом примере длительность и расстояние от начальной точки до первого пункта назначения в результатах составляют 285 секунд и 1616 метров.
Второй этап содержит длительность и расстояние от точки до конечной точки маршрута. В данном примере длительность и расстояние составляют 2466 секунд и 58147 метров.
Укажите исходную точку маршрута, режим движения и модификаторы маршрута.
Вы можете изменить расчёт сводки поиска и маршрута, указав исходную точку маршрута, режим передвижения, модификаторы маршрута и параметры маршрутизации. Режим передвижения и модификаторы маршрута работают так же, как и при расчёте сводки маршрута без указания маршрута, как показано в разделе «Указание параметров маршрута ».
По умолчанию первый отрезок каждого результата содержит расстояние от начальной точки, определяемой ломаной, до каждого места. Однако это значение по умолчанию можно переопределить, явно указав начальную точку маршрута в запросе. Если она указана, первый отрезок всех ответов указывает расстояние и длительность пути от указанной начальной точки маршрута, переопределяя начальную точку, определяемую ломаной.
В следующем примере вы указываете начальную точку маршрута в виде координат Сан-Матео, Калифорния, указываете, что необходимо избегать платных дорог, и устанавливаете количество результатов равным 5:
На следующем изображении показана карта, содержащая полилинию маршрута, новую точку начала координат (голубой маркер) и места в результатах поиска (зелёные маркеры). Обратите внимание, что все результаты находятся вдоль маршрута, но за пределами Сан-Матео:
Попробуйте!
API Explorer позволяет вам делать образцы запросов, чтобы вы могли ознакомиться с API и его параметрами.
Выберите значок API api на правой стороне страницы.
При желании отредактируйте параметры запроса.
Нажмите кнопку «Выполнить» . В диалоговом окне выберите учётную запись, которую вы хотите использовать для отправки запроса.
На панели обозревателя API выберите значок полноэкранного режима, чтобы развернуть окно обозревателя API.
[[["Прост для понимания","easyToUnderstand","thumb-up"],["Помог мне решить мою проблему","solvedMyProblem","thumb-up"],["Другое","otherUp","thumb-up"]],[["Отсутствует нужная мне информация","missingTheInformationINeed","thumb-down"],["Слишком сложен/слишком много шагов","tooComplicatedTooManySteps","thumb-down"],["Устарел","outOfDate","thumb-down"],["Проблема с переводом текста","translationIssue","thumb-down"],["Проблемы образцов/кода","samplesCodeIssue","thumb-down"],["Другое","otherDown","thumb-down"]],["Последнее обновление: 2025-09-04 UTC."],[[["\u003cp\u003eCombine routing summaries with search along a route to get travel duration and distance to places along a route, and from those places to the final destination.\u003c/p\u003e\n"],["\u003cp\u003eUse the Routes API to generate a route polyline, then provide it to Text Search (New) to bias results near the route and calculate routing summaries.\u003c/p\u003e\n"],["\u003cp\u003eInclude \u003ccode\u003eroutingSummaries\u003c/code\u003e in the field mask to receive duration and distance information, and optionally specify \u003ccode\u003eroutingParameters\u003c/code\u003e to customize origin, travel mode, and route modifiers.\u003c/p\u003e\n"],["\u003cp\u003eText Search (New) returns a two-leg trip time: the first leg is from the origin to the place, and the second leg is from the place to the route's final destination.\u003c/p\u003e\n"],["\u003cp\u003eYou can customize the routing summary calculations by providing the routing origin, travel mode, route modifiers, and routing preferences in the request.\u003c/p\u003e\n"]]],[],null,["Combine routing summaries with search along route\n=================================================\n\nYou can combine **routing summary** calculations with **search along a route** .\nIn this case, [Text Search (New)](/maps/documentation/places/web-service/text-search) returns the travel duration and distance to each\nplace in the response, and then from each place to the final destination of the\nroute.\n\nTo use Text Search (New) to calculate the routing summary along with search\nalong a route:\n\n1. Use the Routes API to calculate a route that [returns a route polyline](/maps/documentation/routes/traffic_on_polylines)\n in the response.\n\n2. Use the `searchAlongRouteParameters.polyline.encodedPolyline` parameter to\n pass the route polyline to Text Search (New) to bias the search results to\n the route. The response then contains places that match the search criteria\n and are also located near the specified route.\n\n3. Include `routingSummaries` in the field mask so that the response includes\n the `routingSummaries` array. This array contains the duration and distance\n from the routing origin to each place in the response.\n\n | **Note:** Adding `routingSummaries` in the field mask without also including either the `routingParameters.origin` parameter or the `searchAlongRouteParameters.polyline.encodedPolyline` parameter in the request causes an error.\n\nThe APIs Explorer lets you make live requests so that you can get familiar with\nthe API and the API options: \n[Try it!](#try_it)\n\nBy default, Text Search (New) performs the search along the entire route: \n\n```scdoc\ncurl -X POST -d '{\n \"textQuery\" : \"Spicy Vegetarian Food\",\n \"searchAlongRouteParameters\": {\n \"polyline\": {\n \"encodedPolyline\": \"\u003cvar translate=\"no\"\u003eROUTE_POLYLINE\u003c/var\u003e\"\n }\n }\n}' \\\n-H 'Content-Type: application/json' -H 'X-Goog-Api-Key: API_KEY' \\\n-H 'X-Goog-FieldMask: places.displayName,places.formattedAddress,places.priceLevel,routingSummaries' \\\n'https://places.googleapis.com/v1/places:searchText'\n```\n\nThe response contains two arrays: the `places` array containing the matching\nplaces, and the `routingSummaries` array containing the duration and distance to\ntravel to each place: \n\n```json\n{\n \"places\": [\n {\n \"formattedAddress\": \"1199 El Camino Real, San Bruno, CA 94066, USA\",\n \"priceLevel\": \"PRICE_LEVEL_INEXPENSIVE\",\n \"displayName\": {\n \"text\": \"Vegan Mob - Vegan BBQ and Soul Food\",\n \"languageCode\": \"en\"\n }\n },\n {\n \"formattedAddress\": \"839 Kearny St, San Francisco, CA 94108, USA\",\n \"priceLevel\": \"PRICE_LEVEL_MODERATE\",\n \"displayName\": {\n \"text\": \"Enjoy Vegetarian\",\n \"languageCode\": \"en\"\n }\n },\n ...\n],\n \"routingSummaries\": [\n {\n \"legs\": [\n {\n \"duration\": \"285s\",\n \"distanceMeters\": 1616\n },\n {\n \"duration\": \"2466s\",\n \"distanceMeters\": 58147\n }\n ],\n \"directionsUri\": \"https://www.google.com/maps/dir/37.42268,-122.08473/''/37.77877,-122.38781/data=!4m7!4m6!1m0!1m2!1m1!1s0x808f87f9ede375f5:0xa37171fea1a16b28!1m0!3e0\"\n },\n {\n \"legs\": [\n {\n \"duration\": \"696s\",\n \"distanceMeters\": 4704\n },\n {\n \"duration\": \"2787s\",\n \"distanceMeters\": 58901\n }\n ],\n \"directionsUri\": \"https://www.google.com/maps/dir/37.42268,-122.08473/''/37.77877,-122.38781/data=!4m7!4m6!1m0!1m2!1m1!1s0x808580f4cebdb06f:0xd3af09e5742234f2!1m0!3e0\"\n },\n ...\n ]\n}\n```\n\nFor each entry in the `legs` array, Text Search (New) returns a **two-leg** trip\ntime:\n\n- The first leg contains the travel duration and distance from the origin to\n the place. In this example, the duration and distance from the origin to the\n first place in the results is 285 seconds and 1616 meters.\n\n- The second leg contains the travel duration and distance from the place to\n the route destination. In this example, the duration and distance is\n 2466 seconds and 58147 meters.\n\n| **Note:** This response also includes the Preview (pre-GA) `directionsUri` field in the routing summary for each place. This field contains a link to open directions to the place in Google Maps. The polyline origin or the `routingParameters.origin` parameter specifies directions origin, the polyline destination specifies the directions destination, and the travel mode is drive. The directions start at the origin, proceed to the place as a waypoint, and end at the route destination.\n| This product or feature is in Preview (pre-GA). Pre-GA products and features might have limited support, and changes to pre-GA products and features might not be compatible with other pre-GA versions. Pre-GA Offerings are covered by the [Google\n| Maps Platform Service Specific Terms](https://cloud.google.com/maps-platform/terms/maps-service-terms). For more information, see the [launch stage\n| descriptions](/maps/launch-stages).\n\nSpecify the routing origin, travel mode, and route modifiers\n------------------------------------------------------------\n\nYou can modify the search and routing summary calculation by specifying the\nrouting origin, travel mode, route modifiers, and routing preferences. The\ntravel mode and route modifiers work the same as for calculating routing\nsummaries without specifying a route as shown in the [Specify travel\noptions](/maps/documentation/places/web-service/routing-summary#travel-options) topic.\n\nBy default, the first leg of each result contains the distance from the origin\ndefined by the polyline to each place. However, you can override that default by\nexplicitly specifying a routing origin in the request. If specified, the first\nleg of all responses specifies the distances and duration from the specified\nrouting origin, overriding the origin from the polyline.\n\nIn the next example, you specify a routing origin as the coordinates of San\nMateo, CA, specify to avoid tolls, and set the number of results to 5: \n\n```scdoc\n curl -X POST -d '{\n \"textQuery\" : \"Spicy Vegetarian Food\",\n \"maxResultCount\": 5,\n \"searchAlongRouteParameters\": {\n \"polyline\": {\n \"encodedPolyline\": \"\u003cvar translate=\"no\"\u003eROUTE_POLYLINE\u003c/var\u003e\"\n }\n },\n \"routingParameters\": {\n \"origin\": {\n \"latitude\": 37.56617,\n \"longitude\": -122.30870\n },\n \"travelMode\":\"DRIVE\",\n \"routeModifiers\": {\n \"avoidTolls\": true\n }\n }\n }' \\\n -H 'Content-Type: application/json' -H 'X-Goog-Api-Key: API_KEY' \\\n -H 'X-Goog-FieldMask: places.displayName,places.formattedAddress,places.priceLevel,routingSummaries' \\\n 'https://places.googleapis.com/v1/places:searchText'\n```\n\nThe following image shows a map that contains the route polyline, the new origin\n(light-blue pin), and the places in the search results (green pins). Notice how\nall the results are along the route, but past San Mateo:\n\nTry it!\n-------\n\nThe APIs Explorer lets you make sample requests so\nthat you can get familiar with the API and the API options.\n\n1. Select the API icon api\n on the right side of the page.\n\n2. Optionally edit the request parameters.\n\n3. Select the **Execute** button. In the dialog, choose the account\n that you want to use to make the request.\n\n4. In the APIs Explorer panel, select the fullscreen icon\n fullscreen to expand the APIs Explorer window."]]