Destination — это конкретное место, куда пользователь намеревается добраться или куда хочет направиться. Пункт Destination также включает в себя набор информации, относящейся к этому месту, такой как точки навигации, ориентиры, входы и очертания зданий.
Метод SearchDestinations API геокодирования позволяет получать подробную информацию о различных пунктах назначения на основе различных входных критериев, таких как адрес, идентификатор места или координаты широты и долготы.
Запрос на поиск направлений
Запрос на поиск целевых адресов представляет собой HTTP POST-запрос к URL-адресу в следующем формате:
https://geocode.googleapis.com/v4/geocode/destinations
Передайте все параметры в теле JSON-запроса или в заголовках POST-запроса. Например:
curl -X POST -d '{
"place": "places/ChIJY8sv5-i2j4AR_S6BlDDR42w"
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
Вы можете указать местоположение для поиска пункта назначения одним из трех способов:
- Адрес
- Идентификатор места
- Координаты широты и долготы
Найдите пункт назначения по адресу.
Адрес можно указать в виде неструктурированной строки. Геокодирование адресов не обрабатывает координаты широты и долготы, а также другие неструктурированные строки, не представляющие собой адрес. Запросы, использующие такие строки, не поддерживаются и могут привести к ошибкам или неопределенному поведению. Примеры неподдерживаемых запросов включают следующее:
| тип запроса | Пример |
|---|---|
| Координаты широты и долготы. Вместо этого используйте запрос местоположения . | "37.422131,-122.084801" |
| Слишком много понятий или ограничений, например, названия нескольких мест, дорог или городов в одном запросе. | «Маркет-стрит, аэропорт Сан-Франциско Сан-Хосе» |
| Элементы почтового адреса, не отображаемые на Google Maps. | «Адрес: Джон Смит, Мейн-стрит, 123» "Адрес: 13, Сан-Франциско" |
| Названия предприятий, сетей или категорий в сочетании с указанием мест, где эти организации недоступны. | «Магазин Tesco недалеко от Далласа, штат Техас» |
| Неоднозначные запросы с множественными интерпретациями | "Сдача зарядного устройства" |
| Исторические названия больше не используются. | «Мидлсекс, Соединенное Королевство» |
| Негеопространственные элементы или намерения | «Сколько лодок находится в гавани Вентуры?» |
| Неофициальные или самозваные названия | «Дженга» "Хелтер Скелтер" |
| Крупные политические образования (города, штаты, страны) | «Нью-Йорк» "Калифорния" "США" |
| Маршруты без указания конкретных адресов | «1-я авеню, Нью-Йорк, штат Нью-Йорк» "I-95" |
curl -X POST -d '{
"addressQuery": {
"addressQuery": "601 S Bernardo Ave, Sunnyvale, CA 94087, USA"
}
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
или в качестве postalAddress :
curl -X POST -d '{
"addressQuery": {
"address": {
"addressLines": ["601 S Bernardo Ave"],
"locality": "Sunnyvale",
"postalCode": "94087",
"administrativeArea": "CA",
"regionCode": "US"
}
}
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
Формат postalAddress обычно используется при обработке адресных компонентов, введенных в HTML-форму.
Найдите пункт назначения по идентификатору места.
Вы можете получить доступ к месту назначения, указав его идентификатор :
curl -X POST -d '{
"place": "places/ChIJY8sv5-i2j4AR_S6BlDDR42w"
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
Поддерживаемые идентификаторы мест
Метод поиска пунктов назначения лучше всего работает с идентификаторами мест, представляющими конкретные, доступные для навигации пункты назначения. Как правило, поддерживаются идентификаторы мест таких типов, как establishment , point_of_interest , « premise , street_address и subpremise ». Идентификаторы мест, не представляющие конкретные местоположения, например, определяемые по диапазонам адресов (например, «Главная улица, 10-20»), участки маршрута без конкретного номера или коды с плюсом, не поддерживаются. Идентификаторы мест для результатов, имеющих слишком большую площадь (например, «Тихий океан»), также не поддерживаются.
Используйте автозаполнение (новая функция) для поиска пунктов назначения.
Для обеспечения совместимости используйте функцию автозаполнения (новая) , чтобы найти идентификаторы мест для использования с функциями поиска. При использовании функции автозаполнения (новая) следует фильтровать результаты по типу, используя параметр includedPrimaryTypes . Функции поиска поддерживают идентификаторы мест, возвращаемые функцией автозаполнения (новая) с использованием следующего рекомендуемого фильтра:
"includedPrimaryTypes": [ "establishment", "point_of_interest", "premise", "street_address", "subpremise" ]
Кроме того, не следует устанавливать флаг include_pure_service_area_businesses в true в запросе автозаполнения (нового запроса).
Найдите пункт назначения по местоположению.
Для поиска пункта назначения укажите координаты широты и долготы:
curl -X POST -d '{
"locationQuery": {
"location": {
"latitude": 37.37348780,
"longitude": -122.05678064
}
}
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
Используйте OAuth для отправки запроса.
API геокодирования версии 4 поддерживает аутентификацию OAuth 2.0 . Для использования OAuth с API геокодирования необходимо присвоить токену OAuth правильную область действия (scope). API геокодирования поддерживает следующие области действия для использования с методом Destinations:
-
https://www.googleapis.com/auth/maps-platform.geocode— Использовать со всеми методами API геокодирования.
Кроме того, вы можете использовать общую область видимости https://www.googleapis.com/auth/cloud-platform для всех методов API геокодирования. Эта область видимости полезна во время разработки, но не в продакшене, поскольку это общая область видимости, предоставляющая доступ ко всем методам.
Для получения дополнительной информации и примеров см. раздел «Использование OAuth» .
Ответы на запросы о направлениях поиска
В ответе на запрос «Поиск мест назначения» предоставляется подробная, локальная информация о местоположении.
Объекты PlaceView в ответе Search Destinations (такие как primary , элементы в containingPlaces и landmarks ) используют поля для указания типа места:
-
types: Массив строк, указывающих тип(ы) места. -
primaryType: Строка, указывающая основной тип места.
Возможные строковые значения для обоих types и primaryType берутся из таблиц A и B на странице «Типы мест (новые)».
В этом разделе описаны основные поля ответа. Полную информацию обо всех полях ответа см. в справочнике API .
primary
Основное место, указанное в запросе.
addressComponents
Массив, содержащий отдельные компоненты, относящиеся к данному адресу.
Каждый компонент адреса обычно содержит следующие поля:
- массив
types[]указывает тип компонента адреса. См. список поддерживаемых типов . -
longText— это полное текстовое описание или название компонента адреса, возвращаемое геокодером. -
shortText— это сокращённое текстовое название компонента адреса, если таковое имеется. Например, компонент адреса для штата Аляска может иметьlongTextсо словом "Alaska" иshortTextсо словом "AK", используя двухбуквенное почтовое сокращение. -
languageCode— это язык, используемый для форматирования данного компонента, в нотации CLDR.
containingPlaces
Крупные объекты, частью которых является основной объект назначения (например, торговый центр, в котором расположен магазин).
subDestinations
Более конкретные места в пределах основного пункта назначения (например, квартиры в здании).
entrances
Объекты в массиве entrances[] имеют следующие поля:
locationОтдельная пара координат широты и долготы, определяющая местоположение точки входа и выхода в какое-либо место.
entrance_tags[]Массив тегов входа, описывающий его характеристики. Поддерживаются следующие значения:
-
"PREFERRED"
Указывает на то, что этот вход, вероятно, обеспечивает физический доступ к возвращаемому месту. У одного места может быть несколько предпочтительных входов. Если у входа нет этой метки, это означает, что вход физически находится в том же здании, но не обязательно обеспечивает доступ к месту.
Например, если возвращенное место — это ресторан в торговом центре, то в поле
"PREFERRED"будут указаны входы в сам ресторан, а остальные возвращенные входы будут другими входами в здание, например, входами в другие рестораны в торговом центре.Если возвращаемое помещение представляет собой само здание,
"PREFERRED"входами будут те, которые ведут в «главную» часть здания. Например, в торговом центре"PREFERRED"входами будут те, которые обеспечивают доступ в главный вестибюль, но если вход ведет только в магазин сбоку здания, он не будет считаться"PREFERRED".-
streetViewThumbnailиstreetViewAnnotationПараметры для статического API Street View , позволяющие отображать релевантные изображения для этих мест. Узнайте больше об этих полях .
structureType
Тип строения, который представляет собой это место.
POINTТочечное местоположение.
SECTIONПодразделение здания.
BUILDINGЗдание.
GROUNDSБольшая территория, обычно включающая в себя несколько зданий, таких как университетский кампус, жилой комплекс или торговый центр.
navigationPoints
Поле navigationPoints в ответе геокодирования содержит список точек, полезных для навигации к месту назначения. В частности, их следует использовать в качестве начальной или конечной точки при построении маршрута по дорожной сети от или к этому месту.
Каждая точка навигации содержит следующие значения:
-
navigationPointToken— это токен, содержащий контекстную информацию из поляnavigationPoints. Вы можете отправлять этот токен в API маршрутизации и навигации, чтобы улучшить работу с маршрутизацией и речной сетью в вашем приложении. Дополнительную информацию см. в разделе «Маршрутизация с использованием токенов точек навигации» . - В
locationуказаны широта и долгота точки навигации. Это место всегда находится очень близко к дорожной сети и представляет собой идеальную отправную или остановочную точку для навигации в определенное место и обратно. Точка намеренно немного смещена относительно центральной линии дороги, чтобы четко обозначить сторону дороги, где находится это место. -
travelModes— это список режимов передвижения, с помощью которых можно получить доступ к точке навигации:-
"DRIVE"— это режим движения, соответствующий указаниям по маршруту. -
"WALK"— это режим передвижения, соответствующий пешеходному маршруту.
-
- Список вариантов использования, поддерживаемых точкой навигации, называется
usages. Варианты использования могут быть следующими:-
"DROPOFF" -
"PICKUP" -
"PARKING"
-
Для посадки и высадки используйте точку навигации, где режим движения — DRIVE , а режим использования — PICKUP или DROPOFF . Если точки посадки или высадки недоступны, используйте верхнюю точку навигации для движения.
-
streetViewThumbnailиentranceAnnotationпредоставляют параметры для статического API Street View , позволяя отображать соответствующие изображения для этих мест. Узнайте больше об этих полях .
-
altitude_metersсодержит высоту навигационной точки в метрах относительно эллипсоида WGS-84 . В случаях, когда участки дороги расположены вертикально друг над другом, используйте полеaltitude_meters, чтобы выбрать наиболее подходящий участок дороги для навигации вашей системы.
landmarks
Примечательные места поблизости, которые помогут пользователям сориентироваться в окрестностях места назначения.
arrivalSummary
Аналитические данные, полученные с помощью ИИ, помогут вам при прибытии. См. сводные данные, созданные с помощью ИИ .
parkingOptions
Подробная информация о парковке.
Формат ответа
Функция SearchDestinations возвращает объект SearchDestinationsResponse в следующем формате JSON:
{ "destinations": [ { "primary": { "place": "places/ChIJY8sv5-i2j4AR_S6BlDDR42w", "displayName": { "text": "Arby's", "languageCode": "en" }, "primaryType": "fast_food_restaurant", "types": [ "fast_food_restaurant", "sandwich_shop", "deli", "meal_takeaway", "food_delivery", "american_restaurant", "restaurant", "food_store", "store", "food", "point_of_interest", "establishment" ], "formattedAddress": "Arby's, 601 S Bernardo Ave, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "601 S Bernardo Ave" ] }, "structureType": "BUILDING", "location": { "latitude": 37.3734545, "longitude": -122.05693269999998 }, "displayPolygon": { "type": "Polygon", "coordinates": [ [ [ -122.056930138027, 37.3735253692531 ], [ -122.056960139391, 37.3735372663597 ], [ -122.056994129366, 37.3734828786847 ], [ -122.056969677395, 37.3734731161089 ], [ -122.057061762447, 37.3733261309656 ], [ -122.056979388817, 37.3732935577128 ], [ -122.056798860285, 37.3735818838642 ], [ -122.056875858081, 37.3736121235316 ], [ -122.056930138027, 37.3735253692531 ] ] ] } }, "containingPlaces": [ { "place": "places/ChIJYfdAFum2j4ARIcL2tjME3Sw", "displayName": { "text": "Cherry Chase Shopping Center", "languageCode": "en" }, "primaryType": "shopping_mall", "types": [ "shopping_mall", "point_of_interest", "establishment" ], "formattedAddress": "Cherry Chase Shopping Center, 663 S Bernardo Ave, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087-1020", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "663 S Bernardo Ave" ] }, "structureType": "GROUNDS", "location": { "latitude": 37.3731231, "longitude": -122.0578211 }, "displayPolygon": { "type": "Polygon", "coordinates": [ [ [ -122.057112227103, 37.3714618008523 ], [ -122.057076849821, 37.3715743611411 ], [ -122.056963607756, 37.3719081793948 ], [ -122.056865279559, 37.3722026053835 ], [ -122.056687872374, 37.3727258358476 ], [ -122.056580005889, 37.3730511370747 ], [ -122.056498845827, 37.3732994782583 ], [ -122.056338259713, 37.3737878663325 ], [ -122.056618678291, 37.373887693582 ], [ -122.056912102521, 37.3740010327191 ], [ -122.057532418159, 37.3742476426462 ], [ -122.057673926626, 37.3742441740031 ], [ -122.057735663106, 37.3742328516943 ], [ -122.057766531332, 37.3742220604378 ], [ -122.057797572967, 37.37420520725 ], [ -122.057828267759, 37.3741852342085 ], [ -122.058060299297, 37.3740060842535 ], [ -122.058199726081, 37.3737861673422 ], [ -122.05836707267, 37.373524542556 ], [ -122.058569622393, 37.3732018598683 ], [ -122.0587638478, 37.3728890198039 ], [ -122.058934661823, 37.3726036257774 ], [ -122.059164956851, 37.3722498383629 ], [ -122.058997784906, 37.3721804442035 ], [ -122.057936479838, 37.3717605636234 ], [ -122.057495827092, 37.3715860151634 ], [ -122.057112227103, 37.3714618008523 ] ] ] } } ], "landmarks": [ { "place": { "place": "places/ChIJXXTe7Oi2j4ARoMTA-D6Hjpg", "displayName": { "text": "Chase Bank", "languageCode": "en" }, "primaryType": "bank", "types": [ "bank", "atm", "finance", "point_of_interest", "establishment" ], "formattedAddress": "Chase Bank, 1234 W El Camino Real, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "1234 W El Camino Real" ] }, "structureType": "POINT", "location": { "latitude": 37.373579, "longitude": -122.05752700000001 } }, "relationalDescription": { "text": "Near Chase Bank", "languageCode": "en" }, "tags": [ "ARRIVAL", "ADDRESS" ], "straightLineDistanceMeters": 61.182193756103516, "travelDistanceMeters": 63.075645446777344 }, { "place": { "place": "places/ChIJteQ0Fum2j4ARGi3tqK4Zm14", "displayName": { "text": "Safeway", "languageCode": "en" }, "primaryType": "grocery_store", "types": [ "grocery_store", "butcher_shop", "florist", "deli", "supermarket", "bakery", "food_delivery", "market", "manufacturer", "food_store", "store", "food", "service", "point_of_interest", "establishment" ], "formattedAddress": "Safeway, 639 S Bernardo Ave, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "639 S Bernardo Ave" ] }, "structureType": "POINT", "location": { "latitude": 37.3727912, "longitude": -122.0581172 } }, "relationalDescription": { "text": "Around the corner from Safeway", "languageCode": "en" }, "tags": [ "ARRIVAL", "ADDRESS" ], "straightLineDistanceMeters": 158.65606689453125, "travelDistanceMeters": 131.1669921875 }, { "place": { "place": "places/ChIJu-PSYui2j4ARNiwOwBApGqk", "displayName": { "text": "Oil Changers", "languageCode": "en" }, "types": [ "car_repair", "service", "point_of_interest", "establishment" ], "formattedAddress": "Oil Changers, 1240 W El Camino Real, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "1240 W El Camino Real" ] }, "structureType": "POINT", "location": { "latitude": 37.3743054, "longitude": -122.0584272 } }, "relationalDescription": { "text": "Down the road from Oil Changers", "languageCode": "en" }, "tags": [ "ARRIVAL" ], "straightLineDistanceMeters": 140.52459716796875, "travelDistanceMeters": 143.24220275878906 }, { "place": { "place": "places/ChIJKRbl5oG3j4ARwuvPGUmtCj0", "displayName": { "text": "Apni Mandi Farmers Market Sunnyvale", "languageCode": "en" }, "primaryType": "grocery_store", "types": [ "grocery_store", "cake_shop", "supermarket", "asian_grocery_store", "indian_restaurant", "meal_takeaway", "bakery", "manufacturer", "wholesaler", "restaurant", "food_store", "store", "food", "point_of_interest", "establishment" ], "formattedAddress": "Apni Mandi Farmers Market Sunnyvale, 1111 W El Camino Real, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087-1056", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "1111 W El Camino Real" ] }, "structureType": "POINT", "location": { "latitude": 37.3737199, "longitude": -122.0522958 } }, "relationalDescription": { "text": "Near Apni Mandi Farmers Market Sunnyvale", "languageCode": "en" }, "tags": [ "ADDRESS" ], "straightLineDistanceMeters": 410.37435913085938, "travelDistanceMeters": 479.49893188476562 }, { "place": { "place": "places/ChIJ8enMlui2j4AR2xXK5EHDhBs", "displayName": { "text": "Starbird Chicken", "languageCode": "en" }, "primaryType": "chicken_restaurant", "types": [ "chicken_restaurant", "fast_food_restaurant", "restaurant", "food", "point_of_interest", "establishment" ], "formattedAddress": "Starbird Chicken, 1241 W El Camino Real, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087-1028", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "1241 W El Camino Real" ] }, "structureType": "BUILDING", "location": { "latitude": 37.3746764, "longitude": -122.05708860000001 }, "displayPolygon": { "coordinates": [ [ [ -122.057003840785, 37.3747648209809 ], [ -122.057136852459, 37.3747919153144 ], [ -122.057205005705, 37.3745815131859 ], [ -122.057071994114, 37.3745544186944 ], [ -122.057003840785, 37.3747648209809 ] ] ], "type": "Polygon" } }, "relationalDescription": { "text": "Near Starbird Chicken", "languageCode": "en" }, "tags": [ "ADDRESS" ], "straightLineDistanceMeters": 87.348007202148438, "travelDistanceMeters": 214.08084106445312 } ], "entrances": [ { "location": { "latitude": 37.3735328, "longitude": -122.05694879999999 }, "tags": [ "PREFERRED" ], "place": "places/ChIJY8sv5-i2j4AR_S6BlDDR42w" } ], "navigationPoints": [ { "navigationPointToken": "ChIJeMt61tqvQkARWT2716SDXsASEgljyy_n6LaPgBH9LoGUMNHjbBoSCWPLL-foto-AEf0ugZQw0eNsIhIJhf5y6ei2j4ARz7yBW5KAPI4", "location": { "latitude": 37.3738659, "longitude": -122.05693620000001 }, "travelModes": [ "DRIVE", "WALK" ], "usages": [ "PARKING" ] } ] } ] }
Необходимые параметры
- В API-запросе должен присутствовать один из следующих трех параметров, указывающий адрес, место или местоположение, для которого необходимо выполнить поиск:
-
addressQuery- адрес для поиска. -
place- идентификатор места, которое нужно найти. -
locationQuery- координаты широты и долготы местоположения, которое необходимо найти.
-
FieldMask
Укажите список полей, которые должны быть возвращены в ответе, создав маску полей ответа . Передайте маску полей ответа методу, используя параметр URL
$fieldsилиfields, или используя заголовок HTTPX-Goog-FieldMask. Например, приведенный ниже запрос вернет только входы, точки навигации и идентификатор места основного пункта назначения.curl -X POST -d '{"place": "places/ChIJG3kh4hq6j4AR_XuFQnV0_t8"}' \ -H "X-Goog-Api-Key: API_KEY" \ -H "Content-Type: application/json" \ -H "X-Goog-FieldMask: destinations.entrances,destinations.navigationPoints,destinations.primary.place" \ https://geocode.googleapis.com/v4/geocode/destinationsВ ответе отсутствует список возвращаемых полей по умолчанию. Если вы опустите маску поля, метод вернет ошибку. Установите маску поля на
*, чтобы вернуть все поля. Дополнительные сведения см. в разделе «Выбор возвращаемых полей» .
Дополнительные параметры
travelModes
Указывает, какие типы
navigationPointsследует возвращать. Навигационные точки для других режимов передвижения будут отфильтрованы. ЕслиtravelModesне задан, могут быть возвращены навигационные точки для всех режимов передвижения.languageCode
Язык, на котором будут возвращаться результаты.
- См. список поддерживаемых языков . Google часто обновляет список поддерживаемых языков, поэтому этот список может быть неполным.
- Если
languageCodeне указан, API по умолчанию используетen. Если вы укажете недопустимый код языка, API вернет ошибкуINVALID_ARGUMENT. - API делает все возможное, чтобы предоставить уличный адрес, понятный как пользователю, так и местным жителям. Для достижения этой цели он возвращает уличные адреса на местном языке, при необходимости транслитерированные в письменность, понятную пользователю, с учетом предпочтительного языка. Все остальные адреса возвращаются на предпочтительном языке. Все компоненты адреса возвращаются на одном языке, который выбирается из первого компонента.
- Если имя недоступно на предпочитаемом языке, API использует наиболее близкое совпадение.
- Предпочитаемый язык оказывает незначительное влияние на набор результатов, которые API выбирает для возврата, и на порядок их возврата. Геокодер по-разному интерпретирует сокращения в зависимости от языка, например, сокращения для типов улиц или синонимы, которые могут быть допустимы в одном языке, но не в другом.
regionCode
Региональный код представляет собой двухсимвольное значение кода CLDR . Значение по умолчанию отсутствует. Большинство кодов CLDR идентичны кодам ISO 3166-1.
При геокодировании адреса ( прямое геокодирование ) этот параметр может влиять на результаты работы сервиса, но не ограничивать их полностью указанным регионом. При геокодировании местоположения ( обратное геокодирование или геокодирование места ) этот параметр может использоваться для форматирования адреса. Во всех случаях этот параметр может влиять на результаты в соответствии с действующим законодательством.
placeFilter
Позволяет фильтровать результаты поиска
locationQueryв соответствии с вашими требованиями, например, возвращать только объекты, являющиеся зданиями, или только объекты, имеющие четкие адреса.Фильтрация по структурной детализации
Фильтр
structureTypeпозволяет указать тип структур, возвращаемых запросом:- Изолирование зданий : используйте
"structureType": "BUILDING", чтобы отобразить контуры зданий на карте или получить подробную информацию о конкретном сооружении. - Понимание комплексов : используйте
"structureType": "GROUNDS", чтобы гарантировать, что основным результатом будет вся территория комплекса. Это полезно при запросах к большим территориям, таким как университетские кампусы или торговые центры. - При работе с отдельными элементами/секциями : используйте
"structureType": "SECTION", чтобы определить секции внутри здания.
Убедитесь в наличии полезных адресов.
Не все населенные пункты имеют четкие адреса на уровне улицы. Фильтр
addressabilityпомогает контролировать качество адресов в результатах поиска:- Требуется четкий основной адрес : Чтобы гарантировать, что основной результат поиска всегда будет иметь адрес или название улицы, используйте
"addressability": "PRIMARY". Это полезно для навигации или отображения информации, где четкий адрес имеет решающее значение. - Разрешить адреса в дополнительных пунктах назначения : В случаях, когда основное место может не иметь адреса, но находящиеся внутри него объекты имеют адрес (например, квартиры в здании),
"addressability": "WEAK"гарантирует, что по крайней мере основное место или один из его дополнительных пунктов назначения имеет адрес. - Любой результат : Если наличие адреса не имеет значения для вашего случая, используйте
"addressability": "ANY". Это настоятельно рекомендуется, когда вам нужны только геометрические атрибуты, такие как контуры зданий и точки навигации, поскольку это повышает точность результатов.
Пример: Фильтрация зданий, имеющих адресную структуру.
curl -X POST -d '{ "locationQuery": { "location": { "latitude": 37.37348780, "longitude": -122.05678064 }, "placeFilter": { "structureType": "BUILDING", "addressability": "PRIMARY" } }, "languageCode": "en" }' \\ -H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \\ -H "X-Goog-FieldMask: place" \\ https://geocode.googleapis.com/v4/geocode/destinations- Изолирование зданий : используйте
Destination — это конкретное место, куда пользователь намеревается добраться или куда хочет направиться. Пункт Destination также включает в себя набор информации, относящейся к этому месту, такой как точки навигации, ориентиры, входы и очертания зданий.
Метод SearchDestinations API геокодирования позволяет получать подробную информацию о различных пунктах назначения на основе различных входных критериев, таких как адрес, идентификатор места или координаты широты и долготы.
Запрос на поиск направлений
Запрос на поиск целевых адресов представляет собой HTTP POST-запрос к URL-адресу в следующем формате:
https://geocode.googleapis.com/v4/geocode/destinations
Передайте все параметры в теле JSON-запроса или в заголовках POST-запроса. Например:
curl -X POST -d '{
"place": "places/ChIJY8sv5-i2j4AR_S6BlDDR42w"
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
Вы можете указать местоположение для поиска пункта назначения одним из трех способов:
- Адрес
- Идентификатор места
- Координаты широты и долготы
Найдите пункт назначения по адресу.
Адрес можно указать в виде неструктурированной строки. Геокодирование адресов не обрабатывает координаты широты и долготы, а также другие неструктурированные строки, не представляющие собой адрес. Запросы, использующие такие строки, не поддерживаются и могут привести к ошибкам или неопределенному поведению. Примеры неподдерживаемых запросов включают следующее:
| тип запроса | Пример |
|---|---|
| Координаты широты и долготы. Вместо этого используйте запрос местоположения . | "37.422131,-122.084801" |
| Слишком много понятий или ограничений, например, названия нескольких мест, дорог или городов в одном запросе. | «Маркет-стрит, аэропорт Сан-Франциско Сан-Хосе» |
| Элементы почтового адреса, не отображаемые на Google Maps. | «Адрес: Джон Смит, Мейн-стрит, 123» "Адрес: 13, Сан-Франциско" |
| Названия предприятий, сетей или категорий в сочетании с указанием мест, где эти организации недоступны. | «Магазин Tesco недалеко от Далласа, штат Техас» |
| Неоднозначные запросы с множественными интерпретациями | "Сдача зарядного устройства" |
| Исторические названия больше не используются. | «Мидлсекс, Соединенное Королевство» |
| Негеопространственные элементы или намерения | «Сколько лодок находится в гавани Вентуры?» |
| Неофициальные или самозваные названия | «Дженга» "Хелтер Скелтер" |
| Крупные политические образования (города, штаты, страны) | «Нью-Йорк» "Калифорния" "США" |
| Маршруты без указания конкретных адресов | «1-я авеню, Нью-Йорк, штат Нью-Йорк» "I-95" |
curl -X POST -d '{
"addressQuery": {
"addressQuery": "601 S Bernardo Ave, Sunnyvale, CA 94087, USA"
}
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
или в качестве postalAddress :
curl -X POST -d '{
"addressQuery": {
"address": {
"addressLines": ["601 S Bernardo Ave"],
"locality": "Sunnyvale",
"postalCode": "94087",
"administrativeArea": "CA",
"regionCode": "US"
}
}
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
Формат postalAddress обычно используется при обработке адресных компонентов, введенных в HTML-форму.
Найдите пункт назначения по идентификатору места.
Вы можете получить доступ к месту назначения, указав его идентификатор :
curl -X POST -d '{
"place": "places/ChIJY8sv5-i2j4AR_S6BlDDR42w"
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
Поддерживаемые идентификаторы мест
Метод поиска пунктов назначения лучше всего работает с идентификаторами мест, представляющими конкретные, доступные для навигации пункты назначения. Как правило, поддерживаются идентификаторы мест таких типов, как establishment , point_of_interest , « premise , street_address и subpremise ». Идентификаторы мест, не представляющие конкретные местоположения, например, определяемые по диапазонам адресов (например, «Главная улица, 10-20»), участки маршрута без конкретного номера или коды с плюсом, не поддерживаются. Идентификаторы мест для результатов, имеющих слишком большую площадь (например, «Тихий океан»), также не поддерживаются.
Используйте автозаполнение (новая функция) для поиска пунктов назначения.
Для обеспечения совместимости используйте функцию автозаполнения (новая) , чтобы найти идентификаторы мест для использования с функциями поиска. При использовании функции автозаполнения (новая) следует фильтровать результаты по типу, используя параметр includedPrimaryTypes . Функции поиска поддерживают идентификаторы мест, возвращаемые функцией автозаполнения (новая) с использованием следующего рекомендуемого фильтра:
"includedPrimaryTypes": [ "establishment", "point_of_interest", "premise", "street_address", "subpremise" ]
Кроме того, не следует устанавливать флаг include_pure_service_area_businesses в true в запросе автозаполнения (нового запроса).
Найдите пункт назначения по местоположению.
Для поиска пункта назначения укажите координаты широты и долготы:
curl -X POST -d '{
"locationQuery": {
"location": {
"latitude": 37.37348780,
"longitude": -122.05678064
}
}
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
Используйте OAuth для отправки запроса.
API геокодирования версии 4 поддерживает аутентификацию OAuth 2.0 . Для использования OAuth с API геокодирования необходимо присвоить токену OAuth правильную область действия (scope). API геокодирования поддерживает следующие области действия для использования с методом Destinations:
-
https://www.googleapis.com/auth/maps-platform.geocode— Использовать со всеми методами API геокодирования.
Кроме того, вы можете использовать общую область видимости https://www.googleapis.com/auth/cloud-platform для всех методов API геокодирования. Эта область видимости полезна во время разработки, но не в продакшене, поскольку это общая область видимости, предоставляющая доступ ко всем методам.
Для получения дополнительной информации и примеров см. раздел «Использование OAuth» .
Ответы на запросы о направлениях поиска
В ответе на запрос «Поиск мест назначения» предоставляется подробная, локальная информация о местоположении.
Объекты PlaceView в ответе Search Destinations (такие как primary , элементы в containingPlaces и landmarks ) используют поля для указания типа места:
-
types: Массив строк, указывающих тип(ы) места. -
primaryType: Строка, указывающая основной тип места.
Возможные строковые значения для обоих types и primaryType берутся из таблиц A и B на странице «Типы мест (новые)».
В этом разделе описаны основные поля ответа. Полную информацию обо всех полях ответа см. в справочнике API .
primary
Основное место, указанное в запросе.
addressComponents
Массив, содержащий отдельные компоненты, относящиеся к данному адресу.
Каждый компонент адреса обычно содержит следующие поля:
- массив
types[]указывает тип компонента адреса. См. список поддерживаемых типов . -
longText— это полное текстовое описание или название компонента адреса, возвращаемое геокодером. -
shortText— это сокращённое текстовое название компонента адреса, если таковое имеется. Например, компонент адреса для штата Аляска может иметьlongTextсо словом "Alaska" иshortTextсо словом "AK", используя двухбуквенное почтовое сокращение. -
languageCode— это язык, используемый для форматирования данного компонента, в нотации CLDR.
containingPlaces
Крупные объекты, частью которых является основной объект назначения (например, торговый центр, в котором расположен магазин).
subDestinations
Более конкретные места в пределах основного пункта назначения (например, квартиры в здании).
entrances
Объекты в массиве entrances[] имеют следующие поля:
locationОтдельная пара координат широты и долготы, определяющая местоположение точки входа и выхода в какое-либо место.
entrance_tags[]Массив тегов входа, описывающий его характеристики. Поддерживаются следующие значения:
-
"PREFERRED"
Указывает на то, что этот вход, вероятно, обеспечивает физический доступ к возвращаемому месту. У одного места может быть несколько предпочтительных входов. Если у входа нет этой метки, это означает, что вход физически находится в том же здании, но не обязательно обеспечивает доступ к месту.
Например, если возвращенное место — это ресторан в торговом центре, то в поле
"PREFERRED"будут указаны входы в сам ресторан, а остальные возвращенные входы будут другими входами в здание, например, входами в другие рестораны в торговом центре.Если возвращаемое помещение представляет собой само здание,
"PREFERRED"входами будут те, которые ведут в «главную» часть здания. Например, в торговом центре"PREFERRED"входами будут те, которые обеспечивают доступ в главный вестибюль, но если вход ведет только в магазин сбоку здания, он не будет считаться"PREFERRED".-
streetViewThumbnailиstreetViewAnnotationПараметры для статического API Street View , позволяющие отображать релевантные изображения для этих мест. Узнайте больше об этих полях .
structureType
Тип строения, который представляет собой это место.
POINTТочечное местоположение.
SECTIONПодразделение здания.
BUILDINGЗдание.
GROUNDSБольшая территория, обычно включающая в себя несколько зданий, таких как университетский кампус, жилой комплекс или торговый центр.
navigationPoints
Поле navigationPoints в ответе геокодирования содержит список точек, полезных для навигации к месту назначения. В частности, их следует использовать в качестве начальной или конечной точки при построении маршрута по дорожной сети от или к этому месту.
Каждая точка навигации содержит следующие значения:
-
navigationPointToken— это токен, содержащий контекстную информацию из поляnavigationPoints. Вы можете отправлять этот токен в API маршрутизации и навигации, чтобы улучшить работу с маршрутизацией и речной сетью в вашем приложении. Дополнительную информацию см. в разделе «Маршрутизация с использованием токенов точек навигации» . - В
locationуказаны широта и долгота точки навигации. Это место всегда находится очень близко к дорожной сети и представляет собой идеальную отправную или остановочную точку для навигации в определенное место и обратно. Точка намеренно немного смещена относительно центральной линии дороги, чтобы четко обозначить сторону дороги, где находится это место. -
travelModes— это список режимов передвижения, с помощью которых можно получить доступ к точке навигации:-
"DRIVE"— это режим движения, соответствующий указаниям по маршруту. -
"WALK"— это режим передвижения, соответствующий пешеходному маршруту.
-
- Список вариантов использования, поддерживаемых точкой навигации, называется
usages. Варианты использования могут быть следующими:-
"DROPOFF" -
"PICKUP" -
"PARKING"
-
Для посадки и высадки используйте точку навигации, где режим движения — DRIVE , а режим использования — PICKUP или DROPOFF . Если точки посадки или высадки недоступны, используйте верхнюю точку навигации для движения.
-
streetViewThumbnailиentranceAnnotationпредоставляют параметры для статического API Street View , позволяя отображать соответствующие изображения для этих мест. Узнайте больше об этих полях .
-
altitude_metersсодержит высоту навигационной точки в метрах относительно эллипсоида WGS-84 . В случаях, когда участки дороги расположены вертикально друг над другом, используйте полеaltitude_meters, чтобы выбрать наиболее подходящий участок дороги для навигации вашей системы.
landmarks
Примечательные места поблизости, которые помогут пользователям сориентироваться в окрестностях места назначения.
arrivalSummary
Аналитические данные, полученные с помощью ИИ, помогут вам при прибытии. См. сводные данные, созданные с помощью ИИ .
parkingOptions
Подробная информация о парковке.
Формат ответа
Функция SearchDestinations возвращает объект SearchDestinationsResponse в следующем формате JSON:
{ "destinations": [ { "primary": { "place": "places/ChIJY8sv5-i2j4AR_S6BlDDR42w", "displayName": { "text": "Arby's", "languageCode": "en" }, "primaryType": "fast_food_restaurant", "types": [ "fast_food_restaurant", "sandwich_shop", "deli", "meal_takeaway", "food_delivery", "american_restaurant", "restaurant", "food_store", "store", "food", "point_of_interest", "establishment" ], "formattedAddress": "Arby's, 601 S Bernardo Ave, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "601 S Bernardo Ave" ] }, "structureType": "BUILDING", "location": { "latitude": 37.3734545, "longitude": -122.05693269999998 }, "displayPolygon": { "type": "Polygon", "coordinates": [ [ [ -122.056930138027, 37.3735253692531 ], [ -122.056960139391, 37.3735372663597 ], [ -122.056994129366, 37.3734828786847 ], [ -122.056969677395, 37.3734731161089 ], [ -122.057061762447, 37.3733261309656 ], [ -122.056979388817, 37.3732935577128 ], [ -122.056798860285, 37.3735818838642 ], [ -122.056875858081, 37.3736121235316 ], [ -122.056930138027, 37.3735253692531 ] ] ] } }, "containingPlaces": [ { "place": "places/ChIJYfdAFum2j4ARIcL2tjME3Sw", "displayName": { "text": "Cherry Chase Shopping Center", "languageCode": "en" }, "primaryType": "shopping_mall", "types": [ "shopping_mall", "point_of_interest", "establishment" ], "formattedAddress": "Cherry Chase Shopping Center, 663 S Bernardo Ave, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087-1020", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "663 S Bernardo Ave" ] }, "structureType": "GROUNDS", "location": { "latitude": 37.3731231, "longitude": -122.0578211 }, "displayPolygon": { "type": "Polygon", "coordinates": [ [ [ -122.057112227103, 37.3714618008523 ], [ -122.057076849821, 37.3715743611411 ], [ -122.056963607756, 37.3719081793948 ], [ -122.056865279559, 37.3722026053835 ], [ -122.056687872374, 37.3727258358476 ], [ -122.056580005889, 37.3730511370747 ], [ -122.056498845827, 37.3732994782583 ], [ -122.056338259713, 37.3737878663325 ], [ -122.056618678291, 37.373887693582 ], [ -122.056912102521, 37.3740010327191 ], [ -122.057532418159, 37.3742476426462 ], [ -122.057673926626, 37.3742441740031 ], [ -122.057735663106, 37.3742328516943 ], [ -122.057766531332, 37.3742220604378 ], [ -122.057797572967, 37.37420520725 ], [ -122.057828267759, 37.3741852342085 ], [ -122.058060299297, 37.3740060842535 ], [ -122.058199726081, 37.3737861673422 ], [ -122.05836707267, 37.373524542556 ], [ -122.058569622393, 37.3732018598683 ], [ -122.0587638478, 37.3728890198039 ], [ -122.058934661823, 37.3726036257774 ], [ -122.059164956851, 37.3722498383629 ], [ -122.058997784906, 37.3721804442035 ], [ -122.057936479838, 37.3717605636234 ], [ -122.057495827092, 37.3715860151634 ], [ -122.057112227103, 37.3714618008523 ] ] ] } } ], "landmarks": [ { "place": { "place": "places/ChIJXXTe7Oi2j4ARoMTA-D6Hjpg", "displayName": { "text": "Chase Bank", "languageCode": "en" }, "primaryType": "bank", "types": [ "bank", "atm", "finance", "point_of_interest", "establishment" ], "formattedAddress": "Chase Bank, 1234 W El Camino Real, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "1234 W El Camino Real" ] }, "structureType": "POINT", "location": { "latitude": 37.373579, "longitude": -122.05752700000001 } }, "relationalDescription": { "text": "Near Chase Bank", "languageCode": "en" }, "tags": [ "ARRIVAL", "ADDRESS" ], "straightLineDistanceMeters": 61.182193756103516, "travelDistanceMeters": 63.075645446777344 }, { "place": { "place": "places/ChIJteQ0Fum2j4ARGi3tqK4Zm14", "displayName": { "text": "Safeway", "languageCode": "en" }, "primaryType": "grocery_store", "types": [ "grocery_store", "butcher_shop", "florist", "deli", "supermarket", "bakery", "food_delivery", "market", "manufacturer", "food_store", "store", "food", "service", "point_of_interest", "establishment" ], "formattedAddress": "Safeway, 639 S Bernardo Ave, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "639 S Bernardo Ave" ] }, "structureType": "POINT", "location": { "latitude": 37.3727912, "longitude": -122.0581172 } }, "relationalDescription": { "text": "Around the corner from Safeway", "languageCode": "en" }, "tags": [ "ARRIVAL", "ADDRESS" ], "straightLineDistanceMeters": 158.65606689453125, "travelDistanceMeters": 131.1669921875 }, { "place": { "place": "places/ChIJu-PSYui2j4ARNiwOwBApGqk", "displayName": { "text": "Oil Changers", "languageCode": "en" }, "types": [ "car_repair", "service", "point_of_interest", "establishment" ], "formattedAddress": "Oil Changers, 1240 W El Camino Real, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "1240 W El Camino Real" ] }, "structureType": "POINT", "location": { "latitude": 37.3743054, "longitude": -122.0584272 } }, "relationalDescription": { "text": "Down the road from Oil Changers", "languageCode": "en" }, "tags": [ "ARRIVAL" ], "straightLineDistanceMeters": 140.52459716796875, "travelDistanceMeters": 143.24220275878906 }, { "place": { "place": "places/ChIJKRbl5oG3j4ARwuvPGUmtCj0", "displayName": { "text": "Apni Mandi Farmers Market Sunnyvale", "languageCode": "en" }, "primaryType": "grocery_store", "types": [ "grocery_store", "cake_shop", "supermarket", "asian_grocery_store", "indian_restaurant", "meal_takeaway", "bakery", "manufacturer", "wholesaler", "restaurant", "food_store", "store", "food", "point_of_interest", "establishment" ], "formattedAddress": "Apni Mandi Farmers Market Sunnyvale, 1111 W El Camino Real, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087-1056", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "1111 W El Camino Real" ] }, "structureType": "POINT", "location": { "latitude": 37.3737199, "longitude": -122.0522958 } }, "relationalDescription": { "text": "Near Apni Mandi Farmers Market Sunnyvale", "languageCode": "en" }, "tags": [ "ADDRESS" ], "straightLineDistanceMeters": 410.37435913085938, "travelDistanceMeters": 479.49893188476562 }, { "place": { "place": "places/ChIJ8enMlui2j4AR2xXK5EHDhBs", "displayName": { "text": "Starbird Chicken", "languageCode": "en" }, "primaryType": "chicken_restaurant", "types": [ "chicken_restaurant", "fast_food_restaurant", "restaurant", "food", "point_of_interest", "establishment" ], "formattedAddress": "Starbird Chicken, 1241 W El Camino Real, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087-1028", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "1241 W El Camino Real" ] }, "structureType": "BUILDING", "location": { "latitude": 37.3746764, "longitude": -122.05708860000001 }, "displayPolygon": { "coordinates": [ [ [ -122.057003840785, 37.3747648209809 ], [ -122.057136852459, 37.3747919153144 ], [ -122.057205005705, 37.3745815131859 ], [ -122.057071994114, 37.3745544186944 ], [ -122.057003840785, 37.3747648209809 ] ] ], "type": "Polygon" } }, "relationalDescription": { "text": "Near Starbird Chicken", "languageCode": "en" }, "tags": [ "ADDRESS" ], "straightLineDistanceMeters": 87.348007202148438, "travelDistanceMeters": 214.08084106445312 } ], "entrances": [ { "location": { "latitude": 37.3735328, "longitude": -122.05694879999999 }, "tags": [ "PREFERRED" ], "place": "places/ChIJY8sv5-i2j4AR_S6BlDDR42w" } ], "navigationPoints": [ { "navigationPointToken": "ChIJeMt61tqvQkARWT2716SDXsASEgljyy_n6LaPgBH9LoGUMNHjbBoSCWPLL-foto-AEf0ugZQw0eNsIhIJhf5y6ei2j4ARz7yBW5KAPI4", "location": { "latitude": 37.3738659, "longitude": -122.05693620000001 }, "travelModes": [ "DRIVE", "WALK" ], "usages": [ "PARKING" ] } ] } ] }
Необходимые параметры
- В API-запросе должен присутствовать один из следующих трех параметров, указывающий адрес, место или местоположение, для которого необходимо выполнить поиск:
-
addressQuery- адрес для поиска. -
place- идентификатор места, которое нужно найти. -
locationQuery- координаты широты и долготы местоположения, которое необходимо найти.
-
FieldMask
Укажите список полей, которые должны быть возвращены в ответе, создав маску полей ответа . Передайте маску полей ответа методу, используя параметр URL
$fieldsилиfields, или используя заголовок HTTPX-Goog-FieldMask. Например, приведенный ниже запрос вернет только входы, точки навигации и идентификатор места основного пункта назначения.curl -X POST -d '{"place": "places/ChIJG3kh4hq6j4AR_XuFQnV0_t8"}' \ -H "X-Goog-Api-Key: API_KEY" \ -H "Content-Type: application/json" \ -H "X-Goog-FieldMask: destinations.entrances,destinations.navigationPoints,destinations.primary.place" \ https://geocode.googleapis.com/v4/geocode/destinationsВ ответе отсутствует список возвращаемых полей по умолчанию. Если вы опустите маску поля, метод вернет ошибку. Установите маску поля на
*, чтобы вернуть все поля. Дополнительные сведения см. в разделе «Выбор возвращаемых полей» .
Дополнительные параметры
travelModes
Указывает, какие типы
navigationPointsследует возвращать. Навигационные точки для других режимов передвижения будут отфильтрованы. ЕслиtravelModesне задан, могут быть возвращены навигационные точки для всех режимов передвижения.languageCode
Язык, на котором будут возвращаться результаты.
- См. список поддерживаемых языков . Google часто обновляет список поддерживаемых языков, поэтому этот список может быть неполным.
- Если
languageCodeне указан, API по умолчанию используетen. Если вы укажете недопустимый код языка, API вернет ошибкуINVALID_ARGUMENT. - API делает все возможное, чтобы предоставить уличный адрес, понятный как пользователю, так и местным жителям. Для достижения этой цели он возвращает уличные адреса на местном языке, при необходимости транслитерированные в письменность, понятную пользователю, с учетом предпочтительного языка. Все остальные адреса возвращаются на предпочтительном языке. Все компоненты адреса возвращаются на одном языке, который выбирается из первого компонента.
- Если имя недоступно на предпочитаемом языке, API использует наиболее близкое совпадение.
- Предпочитаемый язык оказывает незначительное влияние на набор результатов, которые API выбирает для возврата, и на порядок их возврата. Геокодер по-разному интерпретирует сокращения в зависимости от языка, например, сокращения для типов улиц или синонимы, которые могут быть допустимы в одном языке, но не в другом.
regionCode
Региональный код представляет собой двухсимвольное значение кода CLDR . Значение по умолчанию отсутствует. Большинство кодов CLDR идентичны кодам ISO 3166-1.
При геокодировании адреса ( прямое геокодирование ) этот параметр может влиять на результаты работы сервиса, но не ограничивать их полностью указанным регионом. При геокодировании местоположения ( обратное геокодирование или геокодирование места ) этот параметр может использоваться для форматирования адреса. Во всех случаях этот параметр может влиять на результаты в соответствии с действующим законодательством.
placeFilter
Позволяет фильтровать результаты поиска
locationQueryв соответствии с вашими требованиями, например, возвращать только объекты, являющиеся зданиями, или только объекты, имеющие четкие адреса.Фильтрация по структурной детализации
Фильтр
structureTypeпозволяет указать тип структур, возвращаемых запросом:- Изолирование зданий : используйте
"structureType": "BUILDING", чтобы отобразить контуры зданий на карте или получить подробную информацию о конкретном сооружении. - Понимание комплексов : используйте
"structureType": "GROUNDS", чтобы гарантировать, что основным результатом будет вся территория комплекса. Это полезно при запросах к большим территориям, таким как университетские кампусы или торговые центры. - При работе с отдельными элементами/секциями : используйте
"structureType": "SECTION", чтобы определить секции внутри здания.
Убедитесь в наличии полезных адресов.
Не все населенные пункты имеют четкие адреса на уровне улицы. Фильтр
addressabilityпомогает контролировать качество адресов в результатах поиска:- Требуется четкий основной адрес : Чтобы гарантировать, что основной результат поиска всегда будет иметь адрес или название улицы, используйте
"addressability": "PRIMARY". Это полезно для навигации или отображения информации, где четкий адрес имеет решающее значение. - Разрешить адреса в дополнительных пунктах назначения : В случаях, когда основное место может не иметь адреса, но находящиеся внутри него объекты имеют адрес (например, квартиры в здании),
"addressability": "WEAK"гарантирует, что по крайней мере основное место или один из его дополнительных пунктов назначения имеет адрес. - Any Result : If address presence isn't relevant to your use case, use
"addressability": "ANY". This is highly recommended when you only need geometric attributes like building outlines and navigation points, as it improves the accuracy of these results.
Example: Filtering for Addressable Buildings
curl -X POST -d '{ "locationQuery": { "location": { "latitude": 37.37348780, "longitude": -122.05678064 }, "placeFilter": { "structureType": "BUILDING", "addressability": "PRIMARY" } }, "languageCode": "en" }' \\ -H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \\ -H "X-Goog-FieldMask: place" \\ https://geocode.googleapis.com/v4/geocode/destinations- Изолирование зданий : используйте
A Destination refers to a specific location or place that a user intends to reach or navigate towards. A Destination also includes a collection of information related to the location or place, such as navigation points, landmarks, entrances, and building outlines.
The SearchDestinations method of the Geocoding API lets you retrieve detailed information about various destinations based on different input criteria, such as an address, place ID, or latitude and longitude coordinates.
Search destinations request
A search destinations request is an HTTP POST request to a URL in the form:
https://geocode.googleapis.com/v4/geocode/destinations
Pass all parameters in the JSON request body or in headers as part of the POST request. For example:
curl -X POST -d '{
"place": "places/ChIJY8sv5-i2j4AR_S6BlDDR42w"
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
You can specify the location to search for a destination in one of 3 ways:
- Адрес
- Идентификатор места
- Latitude and longitude coordinates
Search for a destination by address
You can specify the address as an unstructured string. Address geocoding does not resolve latitude and longitude coordinates, or other unstructured strings that don't represent an address. Requests using such strings are not supported and may lead to error responses or unspecified behavior. Examples of unsupported queries include the following:
| Query type | Пример |
|---|---|
| Latitude and longitude coordinates. Use a location query instead. | "37.422131,-122.084801" |
| Too many concepts or constraints, such as the names of multiple places, roads, or cities in a single query | "Market Street San Francisco San Jose Airport" |
| Postal address elements not represented on Google Maps | "C/O John Smith 123 Main Street" "PO Box 13 San Francisco" |
| Names of businesses, chains, or categories combined with locations where these entities are not available | "Tesco near Dallas, Texas" |
| Ambiguous queries with multiple interpretations | "Charger drop-off" |
| Historical names no longer in use | "Middlesex United Kingdom" |
| Non-geospatial elements or intent | "How many boats are in Ventura Harbor?" |
| Unofficial or vanity names | "The Jenga" "The Helter Skelter" |
| Large political entities (Cities, States, Countries) | "New York City" "California" "США" |
| Routes without specific addresses | "1st Ave., NYC, NY" "I-95" |
curl -X POST -d '{
"addressQuery": {
"addressQuery": "601 S Bernardo Ave, Sunnyvale, CA 94087, USA"
}
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
or as a postalAddress :
curl -X POST -d '{
"addressQuery": {
"address": {
"addressLines": ["601 S Bernardo Ave"],
"locality": "Sunnyvale",
"postalCode": "94087",
"administrativeArea": "CA",
"regionCode": "US"
}
}
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
You typically use the postalAddress format when processing address components captured in an HTML form.
Search for a destination by place ID
You can retrieve a destination by providing a place ID :
curl -X POST -d '{
"place": "places/ChIJY8sv5-i2j4AR_S6BlDDR42w"
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
Supported Place IDs
The Search Destinations method works best with Place IDs that represent specific, navigable destinations. Place IDs for types such as establishment , point_of_interest , premise , street_address , and subpremise are generally supported. Place IDs that don't represent discrete locations, such as those inferred from address ranges (for example, "10-20 Main St"), sections of a route without a specific number, or plus codes are not supported. Place IDs for results that are too large in area (for example, "Pacific Ocean") are also not supported.
Use Autocomplete (New) with Search Destinations
To ensure compatibility, use Autocomplete (New) to find Place IDs for use with Search Destinations. When using Autocomplete (New), you should filter results by type using the includedPrimaryTypes parameter. Place IDs returned by Autocomplete (New) using the following recommended filter are supported by Search Destinations:
"includedPrimaryTypes": [ "establishment", "point_of_interest", "premise", "street_address", "subpremise" ]
Additionally, you shouldn't set the include_pure_service_area_businesses flag to true in your Autocomplete (New) request.
Search for a destination by location
You can search for a destination by providing latitude and longitude coordinates:
curl -X POST -d '{
"locationQuery": {
"location": {
"latitude": 37.37348780,
"longitude": -122.05678064
}
}
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
Use OAuth to make a request
Geocoding API v4 supports OAuth 2.0 for authentication. To use OAuth with the Geocoding API, the OAuth token must be assigned the correct scope. Geocoding API supports the following scopes for use with the Destinations method:
-
https://www.googleapis.com/auth/maps-platform.geocode— Use with all Geocoding API methods.
Also, you can use the general https://www.googleapis.com/auth/cloud-platform scope for all Geocoding API methods. That scope is useful during development, but not production, because it is a general scope that allows access to all methods.
For more information and examples, see Use OAuth .
Search destinations response
The Search Destinations response provides rich, hyperlocal context about the location.
The PlaceView objects within the Search Destinations response (such as primary , items in containingPlaces , and landmarks ) use fields to indicate the place type:
-
types: An array of strings indicating the type(s) of the place. -
primaryType: A string indicating the primary type of the place.
The possible string values for both types and primaryType are drawn from Table A and Table B on the Place Types (New) page.
This section describes the key response fields. For full details on all response fields, see the API Reference .
primary
The main place identified by the query in the request.
addressComponents
An array containing the separate components applicable to this address.
Each address component typically contains the following fields:
-
types[]is an array indicating the type of the address component. See the list of supported types . -
longTextis the full text description or name of the address component as returned by the Geocoder. -
shortTextis an abbreviated textual name for the address component, if available. For example, an address component for the state of Alaska might have alongTextof "Alaska" and ashortTextof "AK" using the two-letter postal abbreviation. -
languageCodeis the language used to format this component, in CLDR notation.
containingPlaces
Larger entities that the primary destination is part of (for example, a mall containing a store).
subDestinations
More specific locations within the primary destination (for example, apartments in a building).
entrances
The objects in the entrances[] array have the following fields:
locationA single latitude/longitude coordinate pair that defines the location of an entry and exit point into a place.
entrance_tags[]An array of entrance tags that describes characteristics of the entrance. The following value is supported:
-
"PREFERRED"
Indicates this entrance likely provides physical access to the returned place. A place can have multiple preferred entrances. If an entrance does not have this tag, it means the entrance is physically on the same building but does not necessarily provide access to the place.
For example, if the returned place is a restaurant in a strip mall, the
"PREFERRED"entrances will be the ones that lead into the restaurant itself, while the other returned entrances will be other entrances for the building, such as entrances into other restaurants in the strip mall.If the returned place is a building itself, the
"PREFERRED"entrances will be the ones that lead into the "main" part of the building. For example, in a shopping center the"PREFERRED"entrances will be the ones that allow access to the main foyer area, but if an entrance only provides access to a store on the side of the building, it won't be a"PREFERRED"entrance.-
streetViewThumbnailandstreetViewAnnotationParameters for the Street View Static API , allowing you to display relevant imagery for these locations. Learn more about these fields .
structureType
The type of structure that this place represents.
POINTA point location.
SECTIONA subsection of a building.
BUILDINGA building.
GROUNDSA large area that typically contains multiple buildings, such as a university campus, an apartment complex, or a shopping mall.
navigationPoints
The navigationPoints field within the Geocoding response contains a list of points that are useful for navigating to the place. Specifically, they should be used either as the starting or ending points when routing on a road network from or to the place.
Each navigation point contains the following values:
-
navigationPointTokenis a token containing the contextual information in thenavigationPointsfield. You can send this token to routing and navigation APIs to improve routing and river experience in your app. See Route using navigation point tokens for more information. -
locationcontains the latitude, longitude value of the navigation point. This location will always be very close to the road network and represents an ideal stopping or starting point for navigating to and from a place. The point is intentionally slightly offset from the road's centerline to clearly mark the side of the road where the place is located. -
travelModesis a list of travel modes that the navigation point is accessible from:-
"DRIVE"is the travel mode corresponding to driving directions. -
"WALK"is the travel mode corresponding to walking directions.
-
-
usagesis a list of usages supported by the navigation point. Usages can be:-
"DROPOFF" -
"PICKUP" -
"PARKING"
-
For pickups and drop-offs, use the navigation point where travel mode is DRIVE and usage is PICKUP or DROPOFF . If pickup or dropoff points are not available, use the top driving navigation point.
-
streetViewThumbnailandentranceAnnotationprovide parameters for the Street View Static API , allowing you to display relevant imagery for these locations. Learn more about these fields .
-
altitude_meterscontains the altitude of the navigation point in meters relative to the WGS-84 ellipsoid . In instances where there are vertically stacked road segments, use thealtitude_metersfield to pick the best road segment for your system to navigate to.
landmarks
Notable nearby places to help users understand the destination's surroundings.
arrivalSummary
AI-powered insights to assist with arrival. See AI-powered summaries .
parkingOptions
Detailed parking information.
Response format
SearchDestinations returns a SearchDestinationsResponse of the following JSON form:
{ "destinations": [ { "primary": { "place": "places/ChIJY8sv5-i2j4AR_S6BlDDR42w", "displayName": { "text": "Arby's", "languageCode": "en" }, "primaryType": "fast_food_restaurant", "types": [ "fast_food_restaurant", "sandwich_shop", "deli", "meal_takeaway", "food_delivery", "american_restaurant", "restaurant", "food_store", "store", "food", "point_of_interest", "establishment" ], "formattedAddress": "Arby's, 601 S Bernardo Ave, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "601 S Bernardo Ave" ] }, "structureType": "BUILDING", "location": { "latitude": 37.3734545, "longitude": -122.05693269999998 }, "displayPolygon": { "type": "Polygon", "coordinates": [ [ [ -122.056930138027, 37.3735253692531 ], [ -122.056960139391, 37.3735372663597 ], [ -122.056994129366, 37.3734828786847 ], [ -122.056969677395, 37.3734731161089 ], [ -122.057061762447, 37.3733261309656 ], [ -122.056979388817, 37.3732935577128 ], [ -122.056798860285, 37.3735818838642 ], [ -122.056875858081, 37.3736121235316 ], [ -122.056930138027, 37.3735253692531 ] ] ] } }, "containingPlaces": [ { "place": "places/ChIJYfdAFum2j4ARIcL2tjME3Sw", "displayName": { "text": "Cherry Chase Shopping Center", "languageCode": "en" }, "primaryType": "shopping_mall", "types": [ "shopping_mall", "point_of_interest", "establishment" ], "formattedAddress": "Cherry Chase Shopping Center, 663 S Bernardo Ave, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087-1020", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "663 S Bernardo Ave" ] }, "structureType": "GROUNDS", "location": { "latitude": 37.3731231, "longitude": -122.0578211 }, "displayPolygon": { "type": "Polygon", "coordinates": [ [ [ -122.057112227103, 37.3714618008523 ], [ -122.057076849821, 37.3715743611411 ], [ -122.056963607756, 37.3719081793948 ], [ -122.056865279559, 37.3722026053835 ], [ -122.056687872374, 37.3727258358476 ], [ -122.056580005889, 37.3730511370747 ], [ -122.056498845827, 37.3732994782583 ], [ -122.056338259713, 37.3737878663325 ], [ -122.056618678291, 37.373887693582 ], [ -122.056912102521, 37.3740010327191 ], [ -122.057532418159, 37.3742476426462 ], [ -122.057673926626, 37.3742441740031 ], [ -122.057735663106, 37.3742328516943 ], [ -122.057766531332, 37.3742220604378 ], [ -122.057797572967, 37.37420520725 ], [ -122.057828267759, 37.3741852342085 ], [ -122.058060299297, 37.3740060842535 ], [ -122.058199726081, 37.3737861673422 ], [ -122.05836707267, 37.373524542556 ], [ -122.058569622393, 37.3732018598683 ], [ -122.0587638478, 37.3728890198039 ], [ -122.058934661823, 37.3726036257774 ], [ -122.059164956851, 37.3722498383629 ], [ -122.058997784906, 37.3721804442035 ], [ -122.057936479838, 37.3717605636234 ], [ -122.057495827092, 37.3715860151634 ], [ -122.057112227103, 37.3714618008523 ] ] ] } } ], "landmarks": [ { "place": { "place": "places/ChIJXXTe7Oi2j4ARoMTA-D6Hjpg", "displayName": { "text": "Chase Bank", "languageCode": "en" }, "primaryType": "bank", "types": [ "bank", "atm", "finance", "point_of_interest", "establishment" ], "formattedAddress": "Chase Bank, 1234 W El Camino Real, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "1234 W El Camino Real" ] }, "structureType": "POINT", "location": { "latitude": 37.373579, "longitude": -122.05752700000001 } }, "relationalDescription": { "text": "Near Chase Bank", "languageCode": "en" }, "tags": [ "ARRIVAL", "ADDRESS" ], "straightLineDistanceMeters": 61.182193756103516, "travelDistanceMeters": 63.075645446777344 }, { "place": { "place": "places/ChIJteQ0Fum2j4ARGi3tqK4Zm14", "displayName": { "text": "Safeway", "languageCode": "en" }, "primaryType": "grocery_store", "types": [ "grocery_store", "butcher_shop", "florist", "deli", "supermarket", "bakery", "food_delivery", "market", "manufacturer", "food_store", "store", "food", "service", "point_of_interest", "establishment" ], "formattedAddress": "Safeway, 639 S Bernardo Ave, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "639 S Bernardo Ave" ] }, "structureType": "POINT", "location": { "latitude": 37.3727912, "longitude": -122.0581172 } }, "relationalDescription": { "text": "Around the corner from Safeway", "languageCode": "en" }, "tags": [ "ARRIVAL", "ADDRESS" ], "straightLineDistanceMeters": 158.65606689453125, "travelDistanceMeters": 131.1669921875 }, { "place": { "place": "places/ChIJu-PSYui2j4ARNiwOwBApGqk", "displayName": { "text": "Oil Changers", "languageCode": "en" }, "types": [ "car_repair", "service", "point_of_interest", "establishment" ], "formattedAddress": "Oil Changers, 1240 W El Camino Real, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "1240 W El Camino Real" ] }, "structureType": "POINT", "location": { "latitude": 37.3743054, "longitude": -122.0584272 } }, "relationalDescription": { "text": "Down the road from Oil Changers", "languageCode": "en" }, "tags": [ "ARRIVAL" ], "straightLineDistanceMeters": 140.52459716796875, "travelDistanceMeters": 143.24220275878906 }, { "place": { "place": "places/ChIJKRbl5oG3j4ARwuvPGUmtCj0", "displayName": { "text": "Apni Mandi Farmers Market Sunnyvale", "languageCode": "en" }, "primaryType": "grocery_store", "types": [ "grocery_store", "cake_shop", "supermarket", "asian_grocery_store", "indian_restaurant", "meal_takeaway", "bakery", "manufacturer", "wholesaler", "restaurant", "food_store", "store", "food", "point_of_interest", "establishment" ], "formattedAddress": "Apni Mandi Farmers Market Sunnyvale, 1111 W El Camino Real, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087-1056", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "1111 W El Camino Real" ] }, "structureType": "POINT", "location": { "latitude": 37.3737199, "longitude": -122.0522958 } }, "relationalDescription": { "text": "Near Apni Mandi Farmers Market Sunnyvale", "languageCode": "en" }, "tags": [ "ADDRESS" ], "straightLineDistanceMeters": 410.37435913085938, "travelDistanceMeters": 479.49893188476562 }, { "place": { "place": "places/ChIJ8enMlui2j4AR2xXK5EHDhBs", "displayName": { "text": "Starbird Chicken", "languageCode": "en" }, "primaryType": "chicken_restaurant", "types": [ "chicken_restaurant", "fast_food_restaurant", "restaurant", "food", "point_of_interest", "establishment" ], "formattedAddress": "Starbird Chicken, 1241 W El Camino Real, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087-1028", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "1241 W El Camino Real" ] }, "structureType": "BUILDING", "location": { "latitude": 37.3746764, "longitude": -122.05708860000001 }, "displayPolygon": { "coordinates": [ [ [ -122.057003840785, 37.3747648209809 ], [ -122.057136852459, 37.3747919153144 ], [ -122.057205005705, 37.3745815131859 ], [ -122.057071994114, 37.3745544186944 ], [ -122.057003840785, 37.3747648209809 ] ] ], "type": "Polygon" } }, "relationalDescription": { "text": "Near Starbird Chicken", "languageCode": "en" }, "tags": [ "ADDRESS" ], "straightLineDistanceMeters": 87.348007202148438, "travelDistanceMeters": 214.08084106445312 } ], "entrances": [ { "location": { "latitude": 37.3735328, "longitude": -122.05694879999999 }, "tags": [ "PREFERRED" ], "place": "places/ChIJY8sv5-i2j4AR_S6BlDDR42w" } ], "navigationPoints": [ { "navigationPointToken": "ChIJeMt61tqvQkARWT2716SDXsASEgljyy_n6LaPgBH9LoGUMNHjbBoSCWPLL-foto-AEf0ugZQw0eNsIhIJhf5y6ei2j4ARz7yBW5KAPI4", "location": { "latitude": 37.3738659, "longitude": -122.05693620000001 }, "travelModes": [ "DRIVE", "WALK" ], "usages": [ "PARKING" ] } ] } ] }
Required parameters
- One of the following 3 parameters must be in the API request, which specifies the address, place, or location to search for a destination:
-
addressQuery- the address to search for. -
place- the place ID of the place to search for. -
locationQuery- the latitude and longitude coordinates of the location to search for.
-
FieldMask
Specify the list of fields to return in the response by creating a response field mask . Pass the response field mask to the method by using the URL parameter
$fieldsorfields, or by using the HTTP headerX-Goog-FieldMask. For example, the below request will return only the entrances, navigation points, and place ID of the primary destination.curl -X POST -d '{"place": "places/ChIJG3kh4hq6j4AR_XuFQnV0_t8"}' \ -H "X-Goog-Api-Key: API_KEY" \ -H "Content-Type: application/json" \ -H "X-Goog-FieldMask: destinations.entrances,destinations.navigationPoints,destinations.primary.place" \ https://geocode.googleapis.com/v4/geocode/destinationsThere is no default list of returned fields in the response. If you omit the field mask, the method returns an error. Set the field mask to
*in order to return all fields. See Choose fields to return for more details.
Optional parameters
travelModes
Specifies which types of
navigationPointsto return. Navigation points for other travel modes will be filtered out. IftravelModesis unset, navigation points of all travel modes can be returned.languageCode
The language in which to return results.
- See the list of supported languages . Google often updates the supported languages, so this list may not be exhaustive.
- If
languageCodeis not supplied, the API defaults toen. If you specify an invalid language code, the API returns anINVALID_ARGUMENTerror. - The API does its best to provide a street address that is readable for both the user and locals. To achieve that goal, it returns street addresses in the local language, transliterated to a script readable by the user if necessary, observing the preferred language. All other addresses are returned in the preferred language. Address components are all returned in the same language, which is chosen from the first component.
- If a name is not available in the preferred language, the API uses the closest match.
- The preferred language has a small influence on the set of results that the API chooses to return, and the order in which they are returned. The geocoder interprets abbreviations differently depending on language, such as the abbreviations for street types, or synonyms that may be valid in one language but not in another.
regionCode
The region code as a two-character CLDR code value. There is no default value. Most CLDR codes are identical to ISO 3166-1 codes.
When geocoding an address, forward geocoding , this parameter can influence, but not fully restrict, results from the service to the specified region. When geocoding a location or a place, reverse geocoding or place geocoding , this parameter can be used to format the address. In all cases, this parameter can affect results based on applicable law.
placeFilter
Lets you filter the results of a
locationQuerysearch to meet your requirements, such as returning only destinations that are buildings or only destinations that have clear addresses.Filter by structural granularity
The
structureTypefilter lets you specify the kind of structures that are returned by the query:- Isolating Buildings : Use
"structureType": "BUILDING"to show building outlines on a map or get details for a specific structure. - Understanding Complexes : Use
"structureType": "GROUNDS"to ensure the primary result is the overall grounds. This is useful when querying for larger areas like university campuses or shopping malls. - Focusing on Units/Sections : Use
"structureType": "SECTION"to identify sections within a building.
Ensure useful addresses
Not all places have clear street-level addresses. The
addressabilityfilter helps you control the quality of addresses in your results:- Require a Clear Primary Address : To ensure the main destination result always has a street-level address or name, use
"addressability": "PRIMARY". This is useful for navigation or display purposes where a clear address is crucial. - Allow Addresses in Sub-Destinations : In cases where the primary place might not have an address, but units within it do (such as apartments in a building),
"addressability": "WEAK"ensures that at least the primary place or one of its sub-destinations has an address. - Any Result : If address presence isn't relevant to your use case, use
"addressability": "ANY". This is highly recommended when you only need geometric attributes like building outlines and navigation points, as it improves the accuracy of these results.
Example: Filtering for Addressable Buildings
curl -X POST -d '{ "locationQuery": { "location": { "latitude": 37.37348780, "longitude": -122.05678064 }, "placeFilter": { "structureType": "BUILDING", "addressability": "PRIMARY" } }, "languageCode": "en" }' \\ -H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \\ -H "X-Goog-FieldMask: place" \\ https://geocode.googleapis.com/v4/geocode/destinations- Isolating Buildings : Use
A Destination refers to a specific location or place that a user intends to reach or navigate towards. A Destination also includes a collection of information related to the location or place, such as navigation points, landmarks, entrances, and building outlines.
The SearchDestinations method of the Geocoding API lets you retrieve detailed information about various destinations based on different input criteria, such as an address, place ID, or latitude and longitude coordinates.
Search destinations request
A search destinations request is an HTTP POST request to a URL in the form:
https://geocode.googleapis.com/v4/geocode/destinations
Pass all parameters in the JSON request body or in headers as part of the POST request. For example:
curl -X POST -d '{
"place": "places/ChIJY8sv5-i2j4AR_S6BlDDR42w"
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
You can specify the location to search for a destination in one of 3 ways:
- Адрес
- Идентификатор места
- Latitude and longitude coordinates
Search for a destination by address
You can specify the address as an unstructured string. Address geocoding does not resolve latitude and longitude coordinates, or other unstructured strings that don't represent an address. Requests using such strings are not supported and may lead to error responses or unspecified behavior. Examples of unsupported queries include the following:
| Query type | Пример |
|---|---|
| Latitude and longitude coordinates. Use a location query instead. | "37.422131,-122.084801" |
| Too many concepts or constraints, such as the names of multiple places, roads, or cities in a single query | "Market Street San Francisco San Jose Airport" |
| Postal address elements not represented on Google Maps | "C/O John Smith 123 Main Street" "PO Box 13 San Francisco" |
| Names of businesses, chains, or categories combined with locations where these entities are not available | "Tesco near Dallas, Texas" |
| Ambiguous queries with multiple interpretations | "Charger drop-off" |
| Historical names no longer in use | "Middlesex United Kingdom" |
| Non-geospatial elements or intent | "How many boats are in Ventura Harbor?" |
| Unofficial or vanity names | "The Jenga" "The Helter Skelter" |
| Large political entities (Cities, States, Countries) | "New York City" "California" "США" |
| Routes without specific addresses | "1st Ave., NYC, NY" "I-95" |
curl -X POST -d '{
"addressQuery": {
"addressQuery": "601 S Bernardo Ave, Sunnyvale, CA 94087, USA"
}
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
or as a postalAddress :
curl -X POST -d '{
"addressQuery": {
"address": {
"addressLines": ["601 S Bernardo Ave"],
"locality": "Sunnyvale",
"postalCode": "94087",
"administrativeArea": "CA",
"regionCode": "US"
}
}
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
You typically use the postalAddress format when processing address components captured in an HTML form.
Search for a destination by place ID
You can retrieve a destination by providing a place ID :
curl -X POST -d '{
"place": "places/ChIJY8sv5-i2j4AR_S6BlDDR42w"
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
Supported Place IDs
The Search Destinations method works best with Place IDs that represent specific, navigable destinations. Place IDs for types such as establishment , point_of_interest , premise , street_address , and subpremise are generally supported. Place IDs that don't represent discrete locations, such as those inferred from address ranges (for example, "10-20 Main St"), sections of a route without a specific number, or plus codes are not supported. Place IDs for results that are too large in area (for example, "Pacific Ocean") are also not supported.
Use Autocomplete (New) with Search Destinations
To ensure compatibility, use Autocomplete (New) to find Place IDs for use with Search Destinations. When using Autocomplete (New), you should filter results by type using the includedPrimaryTypes parameter. Place IDs returned by Autocomplete (New) using the following recommended filter are supported by Search Destinations:
"includedPrimaryTypes": [ "establishment", "point_of_interest", "premise", "street_address", "subpremise" ]
Additionally, you shouldn't set the include_pure_service_area_businesses flag to true in your Autocomplete (New) request.
Search for a destination by location
You can search for a destination by providing latitude and longitude coordinates:
curl -X POST -d '{
"locationQuery": {
"location": {
"latitude": 37.37348780,
"longitude": -122.05678064
}
}
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: *" \
https://geocode.googleapis.com/v4/geocode/destinations
Use OAuth to make a request
Geocoding API v4 supports OAuth 2.0 for authentication. To use OAuth with the Geocoding API, the OAuth token must be assigned the correct scope. Geocoding API supports the following scopes for use with the Destinations method:
-
https://www.googleapis.com/auth/maps-platform.geocode— Use with all Geocoding API methods.
Also, you can use the general https://www.googleapis.com/auth/cloud-platform scope for all Geocoding API methods. That scope is useful during development, but not production, because it is a general scope that allows access to all methods.
For more information and examples, see Use OAuth .
Search destinations response
The Search Destinations response provides rich, hyperlocal context about the location.
The PlaceView objects within the Search Destinations response (such as primary , items in containingPlaces , and landmarks ) use fields to indicate the place type:
-
types: An array of strings indicating the type(s) of the place. -
primaryType: A string indicating the primary type of the place.
The possible string values for both types and primaryType are drawn from Table A and Table B on the Place Types (New) page.
This section describes the key response fields. For full details on all response fields, see the API Reference .
primary
The main place identified by the query in the request.
addressComponents
An array containing the separate components applicable to this address.
Each address component typically contains the following fields:
-
types[]is an array indicating the type of the address component. See the list of supported types . -
longTextis the full text description or name of the address component as returned by the Geocoder. -
shortTextis an abbreviated textual name for the address component, if available. For example, an address component for the state of Alaska might have alongTextof "Alaska" and ashortTextof "AK" using the two-letter postal abbreviation. -
languageCodeis the language used to format this component, in CLDR notation.
containingPlaces
Larger entities that the primary destination is part of (for example, a mall containing a store).
subDestinations
More specific locations within the primary destination (for example, apartments in a building).
entrances
The objects in the entrances[] array have the following fields:
locationA single latitude/longitude coordinate pair that defines the location of an entry and exit point into a place.
entrance_tags[]An array of entrance tags that describes characteristics of the entrance. The following value is supported:
-
"PREFERRED"
Indicates this entrance likely provides physical access to the returned place. A place can have multiple preferred entrances. If an entrance does not have this tag, it means the entrance is physically on the same building but does not necessarily provide access to the place.
For example, if the returned place is a restaurant in a strip mall, the
"PREFERRED"entrances will be the ones that lead into the restaurant itself, while the other returned entrances will be other entrances for the building, such as entrances into other restaurants in the strip mall.If the returned place is a building itself, the
"PREFERRED"entrances will be the ones that lead into the "main" part of the building. For example, in a shopping center the"PREFERRED"entrances will be the ones that allow access to the main foyer area, but if an entrance only provides access to a store on the side of the building, it won't be a"PREFERRED"entrance.-
streetViewThumbnailandstreetViewAnnotationParameters for the Street View Static API , allowing you to display relevant imagery for these locations. Learn more about these fields .
structureType
The type of structure that this place represents.
POINTA point location.
SECTIONA subsection of a building.
BUILDINGA building.
GROUNDSA large area that typically contains multiple buildings, such as a university campus, an apartment complex, or a shopping mall.
navigationPoints
The navigationPoints field within the Geocoding response contains a list of points that are useful for navigating to the place. Specifically, they should be used either as the starting or ending points when routing on a road network from or to the place.
Each navigation point contains the following values:
-
navigationPointTokenis a token containing the contextual information in thenavigationPointsfield. You can send this token to routing and navigation APIs to improve routing and river experience in your app. See Route using navigation point tokens for more information. -
locationcontains the latitude, longitude value of the navigation point. This location will always be very close to the road network and represents an ideal stopping or starting point for navigating to and from a place. The point is intentionally slightly offset from the road's centerline to clearly mark the side of the road where the place is located. -
travelModesis a list of travel modes that the navigation point is accessible from:-
"DRIVE"is the travel mode corresponding to driving directions. -
"WALK"is the travel mode corresponding to walking directions.
-
-
usagesis a list of usages supported by the navigation point. Usages can be:-
"DROPOFF" -
"PICKUP" -
"PARKING"
-
For pickups and drop-offs, use the navigation point where travel mode is DRIVE and usage is PICKUP or DROPOFF . If pickup or dropoff points are not available, use the top driving navigation point.
-
streetViewThumbnailandentranceAnnotationprovide parameters for the Street View Static API , allowing you to display relevant imagery for these locations. Learn more about these fields .
-
altitude_meterscontains the altitude of the navigation point in meters relative to the WGS-84 ellipsoid . In instances where there are vertically stacked road segments, use thealtitude_metersfield to pick the best road segment for your system to navigate to.
landmarks
Notable nearby places to help users understand the destination's surroundings.
arrivalSummary
AI-powered insights to assist with arrival. See AI-powered summaries .
parkingOptions
Detailed parking information.
Response format
SearchDestinations returns a SearchDestinationsResponse of the following JSON form:
{ "destinations": [ { "primary": { "place": "places/ChIJY8sv5-i2j4AR_S6BlDDR42w", "displayName": { "text": "Arby's", "languageCode": "en" }, "primaryType": "fast_food_restaurant", "types": [ "fast_food_restaurant", "sandwich_shop", "deli", "meal_takeaway", "food_delivery", "american_restaurant", "restaurant", "food_store", "store", "food", "point_of_interest", "establishment" ], "formattedAddress": "Arby's, 601 S Bernardo Ave, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "601 S Bernardo Ave" ] }, "structureType": "BUILDING", "location": { "latitude": 37.3734545, "longitude": -122.05693269999998 }, "displayPolygon": { "type": "Polygon", "coordinates": [ [ [ -122.056930138027, 37.3735253692531 ], [ -122.056960139391, 37.3735372663597 ], [ -122.056994129366, 37.3734828786847 ], [ -122.056969677395, 37.3734731161089 ], [ -122.057061762447, 37.3733261309656 ], [ -122.056979388817, 37.3732935577128 ], [ -122.056798860285, 37.3735818838642 ], [ -122.056875858081, 37.3736121235316 ], [ -122.056930138027, 37.3735253692531 ] ] ] } }, "containingPlaces": [ { "place": "places/ChIJYfdAFum2j4ARIcL2tjME3Sw", "displayName": { "text": "Cherry Chase Shopping Center", "languageCode": "en" }, "primaryType": "shopping_mall", "types": [ "shopping_mall", "point_of_interest", "establishment" ], "formattedAddress": "Cherry Chase Shopping Center, 663 S Bernardo Ave, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087-1020", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "663 S Bernardo Ave" ] }, "structureType": "GROUNDS", "location": { "latitude": 37.3731231, "longitude": -122.0578211 }, "displayPolygon": { "type": "Polygon", "coordinates": [ [ [ -122.057112227103, 37.3714618008523 ], [ -122.057076849821, 37.3715743611411 ], [ -122.056963607756, 37.3719081793948 ], [ -122.056865279559, 37.3722026053835 ], [ -122.056687872374, 37.3727258358476 ], [ -122.056580005889, 37.3730511370747 ], [ -122.056498845827, 37.3732994782583 ], [ -122.056338259713, 37.3737878663325 ], [ -122.056618678291, 37.373887693582 ], [ -122.056912102521, 37.3740010327191 ], [ -122.057532418159, 37.3742476426462 ], [ -122.057673926626, 37.3742441740031 ], [ -122.057735663106, 37.3742328516943 ], [ -122.057766531332, 37.3742220604378 ], [ -122.057797572967, 37.37420520725 ], [ -122.057828267759, 37.3741852342085 ], [ -122.058060299297, 37.3740060842535 ], [ -122.058199726081, 37.3737861673422 ], [ -122.05836707267, 37.373524542556 ], [ -122.058569622393, 37.3732018598683 ], [ -122.0587638478, 37.3728890198039 ], [ -122.058934661823, 37.3726036257774 ], [ -122.059164956851, 37.3722498383629 ], [ -122.058997784906, 37.3721804442035 ], [ -122.057936479838, 37.3717605636234 ], [ -122.057495827092, 37.3715860151634 ], [ -122.057112227103, 37.3714618008523 ] ] ] } } ], "landmarks": [ { "place": { "place": "places/ChIJXXTe7Oi2j4ARoMTA-D6Hjpg", "displayName": { "text": "Chase Bank", "languageCode": "en" }, "primaryType": "bank", "types": [ "bank", "atm", "finance", "point_of_interest", "establishment" ], "formattedAddress": "Chase Bank, 1234 W El Camino Real, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "1234 W El Camino Real" ] }, "structureType": "POINT", "location": { "latitude": 37.373579, "longitude": -122.05752700000001 } }, "relationalDescription": { "text": "Near Chase Bank", "languageCode": "en" }, "tags": [ "ARRIVAL", "ADDRESS" ], "straightLineDistanceMeters": 61.182193756103516, "travelDistanceMeters": 63.075645446777344 }, { "place": { "place": "places/ChIJteQ0Fum2j4ARGi3tqK4Zm14", "displayName": { "text": "Safeway", "languageCode": "en" }, "primaryType": "grocery_store", "types": [ "grocery_store", "butcher_shop", "florist", "deli", "supermarket", "bakery", "food_delivery", "market", "manufacturer", "food_store", "store", "food", "service", "point_of_interest", "establishment" ], "formattedAddress": "Safeway, 639 S Bernardo Ave, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "639 S Bernardo Ave" ] }, "structureType": "POINT", "location": { "latitude": 37.3727912, "longitude": -122.0581172 } }, "relationalDescription": { "text": "Around the corner from Safeway", "languageCode": "en" }, "tags": [ "ARRIVAL", "ADDRESS" ], "straightLineDistanceMeters": 158.65606689453125, "travelDistanceMeters": 131.1669921875 }, { "place": { "place": "places/ChIJu-PSYui2j4ARNiwOwBApGqk", "displayName": { "text": "Oil Changers", "languageCode": "en" }, "types": [ "car_repair", "service", "point_of_interest", "establishment" ], "formattedAddress": "Oil Changers, 1240 W El Camino Real, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "1240 W El Camino Real" ] }, "structureType": "POINT", "location": { "latitude": 37.3743054, "longitude": -122.0584272 } }, "relationalDescription": { "text": "Down the road from Oil Changers", "languageCode": "en" }, "tags": [ "ARRIVAL" ], "straightLineDistanceMeters": 140.52459716796875, "travelDistanceMeters": 143.24220275878906 }, { "place": { "place": "places/ChIJKRbl5oG3j4ARwuvPGUmtCj0", "displayName": { "text": "Apni Mandi Farmers Market Sunnyvale", "languageCode": "en" }, "primaryType": "grocery_store", "types": [ "grocery_store", "cake_shop", "supermarket", "asian_grocery_store", "indian_restaurant", "meal_takeaway", "bakery", "manufacturer", "wholesaler", "restaurant", "food_store", "store", "food", "point_of_interest", "establishment" ], "formattedAddress": "Apni Mandi Farmers Market Sunnyvale, 1111 W El Camino Real, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087-1056", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "1111 W El Camino Real" ] }, "structureType": "POINT", "location": { "latitude": 37.3737199, "longitude": -122.0522958 } }, "relationalDescription": { "text": "Near Apni Mandi Farmers Market Sunnyvale", "languageCode": "en" }, "tags": [ "ADDRESS" ], "straightLineDistanceMeters": 410.37435913085938, "travelDistanceMeters": 479.49893188476562 }, { "place": { "place": "places/ChIJ8enMlui2j4AR2xXK5EHDhBs", "displayName": { "text": "Starbird Chicken", "languageCode": "en" }, "primaryType": "chicken_restaurant", "types": [ "chicken_restaurant", "fast_food_restaurant", "restaurant", "food", "point_of_interest", "establishment" ], "formattedAddress": "Starbird Chicken, 1241 W El Camino Real, Sunnyvale, CA 94087, USA", "postalAddress": { "regionCode": "US", "languageCode": "en", "postalCode": "94087-1028", "administrativeArea": "CA", "locality": "Sunnyvale", "addressLines": [ "1241 W El Camino Real" ] }, "structureType": "BUILDING", "location": { "latitude": 37.3746764, "longitude": -122.05708860000001 }, "displayPolygon": { "coordinates": [ [ [ -122.057003840785, 37.3747648209809 ], [ -122.057136852459, 37.3747919153144 ], [ -122.057205005705, 37.3745815131859 ], [ -122.057071994114, 37.3745544186944 ], [ -122.057003840785, 37.3747648209809 ] ] ], "type": "Polygon" } }, "relationalDescription": { "text": "Near Starbird Chicken", "languageCode": "en" }, "tags": [ "ADDRESS" ], "straightLineDistanceMeters": 87.348007202148438, "travelDistanceMeters": 214.08084106445312 } ], "entrances": [ { "location": { "latitude": 37.3735328, "longitude": -122.05694879999999 }, "tags": [ "PREFERRED" ], "place": "places/ChIJY8sv5-i2j4AR_S6BlDDR42w" } ], "navigationPoints": [ { "navigationPointToken": "ChIJeMt61tqvQkARWT2716SDXsASEgljyy_n6LaPgBH9LoGUMNHjbBoSCWPLL-foto-AEf0ugZQw0eNsIhIJhf5y6ei2j4ARz7yBW5KAPI4", "location": { "latitude": 37.3738659, "longitude": -122.05693620000001 }, "travelModes": [ "DRIVE", "WALK" ], "usages": [ "PARKING" ] } ] } ] }
Required parameters
- One of the following 3 parameters must be in the API request, which specifies the address, place, or location to search for a destination:
-
addressQuery- the address to search for. -
place- the place ID of the place to search for. -
locationQuery- the latitude and longitude coordinates of the location to search for.
-
FieldMask
Specify the list of fields to return in the response by creating a response field mask . Pass the response field mask to the method by using the URL parameter
$fieldsorfields, or by using the HTTP headerX-Goog-FieldMask. For example, the below request will return only the entrances, navigation points, and place ID of the primary destination.curl -X POST -d '{"place": "places/ChIJG3kh4hq6j4AR_XuFQnV0_t8"}' \ -H "X-Goog-Api-Key: API_KEY" \ -H "Content-Type: application/json" \ -H "X-Goog-FieldMask: destinations.entrances,destinations.navigationPoints,destinations.primary.place" \ https://geocode.googleapis.com/v4/geocode/destinationsThere is no default list of returned fields in the response. If you omit the field mask, the method returns an error. Set the field mask to
*in order to return all fields. See Choose fields to return for more details.
Optional parameters
travelModes
Specifies which types of
navigationPointsto return. Navigation points for other travel modes will be filtered out. IftravelModesis unset, navigation points of all travel modes can be returned.languageCode
The language in which to return results.
- See the list of supported languages . Google often updates the supported languages, so this list may not be exhaustive.
- If
languageCodeis not supplied, the API defaults toen. If you specify an invalid language code, the API returns anINVALID_ARGUMENTerror. - The API does its best to provide a street address that is readable for both the user and locals. To achieve that goal, it returns street addresses in the local language, transliterated to a script readable by the user if necessary, observing the preferred language. All other addresses are returned in the preferred language. Address components are all returned in the same language, which is chosen from the first component.
- If a name is not available in the preferred language, the API uses the closest match.
- The preferred language has a small influence on the set of results that the API chooses to return, and the order in which they are returned. The geocoder interprets abbreviations differently depending on language, such as the abbreviations for street types, or synonyms that may be valid in one language but not in another.
regionCode
The region code as a two-character CLDR code value. There is no default value. Most CLDR codes are identical to ISO 3166-1 codes.
When geocoding an address, forward geocoding , this parameter can influence, but not fully restrict, results from the service to the specified region. When geocoding a location or a place, reverse geocoding or place geocoding , this parameter can be used to format the address. In all cases, this parameter can affect results based on applicable law.
placeFilter
Lets you filter the results of a
locationQuerysearch to meet your requirements, such as returning only destinations that are buildings or only destinations that have clear addresses.Filter by structural granularity
The
structureTypefilter lets you specify the kind of structures that are returned by the query:- Isolating Buildings : Use
"structureType": "BUILDING"to show building outlines on a map or get details for a specific structure. - Understanding Complexes : Use
"structureType": "GROUNDS"to ensure the primary result is the overall grounds. This is useful when querying for larger areas like university campuses or shopping malls. - Focusing on Units/Sections : Use
"structureType": "SECTION"to identify sections within a building.
Ensure useful addresses
Not all places have clear street-level addresses. The
addressabilityfilter helps you control the quality of addresses in your results:- Require a Clear Primary Address : To ensure the main destination result always has a street-level address or name, use
"addressability": "PRIMARY". This is useful for navigation or display purposes where a clear address is crucial. - Allow Addresses in Sub-Destinations : In cases where the primary place might not have an address, but units within it do (such as apartments in a building),
"addressability": "WEAK"ensures that at least the primary place or one of its sub-destinations has an address. - Any Result : If address presence isn't relevant to your use case, use
"addressability": "ANY". This is highly recommended when you only need geometric attributes like building outlines and navigation points, as it improves the accuracy of these results.
Example: Filtering for Addressable Buildings
curl -X POST -d '{ "locationQuery": { "location": { "latitude": 37.37348780, "longitude": -122.05678064 }, "placeFilter": { "structureType": "BUILDING", "addressability": "PRIMARY" } }, "languageCode": "en" }' \\ -H 'Content-Type: application/json' -H "X-Goog-Api-Key: API_KEY" \\ -H "X-Goog-FieldMask: place" \\ https://geocode.googleapis.com/v4/geocode/destinations- Isolating Buildings : Use