Place Autocomplete
The Places API is also available with the Java Client, Python Client, Go Client and Node.js Client for Google Maps Services. The Places API and the client libraries are for use in server applications.
If you’re building a client-side application, take a look at the Places SDK for Android, the Places SDK for iOS, and the Places Library, Maps JavaScript API.
The Place Autocomplete service is a web service that returns place predictions in response to an HTTP request. The request specifies a textual search string and optional geographic bounds. The service can be used to provide autocomplete functionality for text-based geographic searches, by returning places such as businesses, addresses and points of interest as a user types.
Place Autocomplete requests
The Place Autocomplete service is part of the Places API and shares an API key and quotas with the Places API.
The Place Autocomplete service can match on full words and substrings, resolving place names, addresses, and plus codes. Applications can therefore send queries as the user types, to provide on-the-fly place predictions.
The returned predictions are designed to be presented to the user to aid them in selecting the desired place. You can send a Place Details request for more information about any of the places which are returned.
A Place Autocomplete request is an HTTP URL of the following form:
where output may be either of the following values:
Certain parameters are required to initiate a Place Autocomplete request. As is standard in URLs, all parameters are separated using the ampersand ( & ) character. The list of parameters and their possible values are enumerated below.
Required parameters
input
The text string on which to search. The Place Autocomplete service will return candidate matches based on this string and order results based on their perceived relevance.
Optional parameters
components
A grouping of places to which you would like to restrict your results. Currently, you can use components to filter by up to 5 countries. Countries must be passed as a two character, ISO 3166-1 Alpha-2 compatible country code. For example: components=country:fr would restrict your results to places within France. Multiple countries must be passed as multiple country:XX filters, with the pipe character | as a separator. For example: components=country:us|country:pr|country:vi|country:gu|country:mp would restrict your results to places within the United States and its unincorporated organized territories.
language
The language in which to return results.
location
offset
origin
radius
Defines the distance (in meters) within which to return place results. You may bias results to a specified circle by passing a location and a radius parameter. Doing so instructs the Places service to prefer showing results within that circle; results outside of the defined area may still be displayed.
The radius will automatically be clamped to a maximum value depending on the type of search and other parameters.
sessiontoken
A random string which identifies an autocomplete session for billing purposes.
The session begins when the user starts typing a query, and concludes when they select a place and a call to Place Details is made. Each session can have multiple queries, followed by one place selection. The API key(s) used for each request within a session must belong to the same Google Cloud Console project. Once a session has concluded, the token is no longer valid; your app must generate a fresh token for each session. If the sessiontoken parameter is omitted, or if you reuse a session token, the session is charged as if no session token was provided (each request is billed separately).
We recommend the following guidelines:
strictbounds
types
You may restrict results from a Place Autocomplete request to be of a certain type by passing a types parameter. The parameter specifies a type or a type collection, as listed in the supported types below. If nothing is specified, all types are returned. In general only a single type is allowed. The exception is that you can safely mix the geocode and establishment types, but note that this will have the same effect as specifying no types. The supported types are:
Place Autocomplete examples
A request for establishments containing the string «Amoeba» within an area centered in San Francisco, CA:
Сравнение сервисов для автодополнения адресов в форме
На Хабре не раз поднимался вопрос автодополнения адресов в форме (раз, два, три).
Но какой источник данных выбрать? Я выбрал целых четыре, и решил их сравнить: в одном углу ринга заморские Google Geocode и Google Autococomplete, а в другом отечественные КЛАДР в облаке и DaData подсказки.
DISCLAIMER: Автор никак не причастен к разработчикам ни одного из представленных сервисов.
Google Geocode (Google Maps API)
В примерах к плагину Typeahead в документации к AngularJS Boostrap UI использован именно Google Geocode для автодополнения адреса. Так почему бы не попробовать, если готовый код уже есть?
Делаем get запрос к адресу http://maps.googleapis.com/maps/api/geocode/json с параметрами
В ответ получаем json, парсим его, и вроде всё неплохо. Вот только нам надо ограничить область поиска только Москвой. Добавляем:
к параметрам и получаем интересное поведение:
Какую ахинею не ввёл бы пользователь, Google предложит «Москва, Россия». К тому же, название улицы он предлагает только после ввода третьей-четвертой буквы, а до этого все те же «Москва, Россия».
Можно ограничить результаты с помощью параметра ‘bounds’ (координаты юго-западного и северо-восточного угла рамки, внутри которой производить геокодирование), но это нестрогое ограничение, поэтому результаты будут появляться и из других областей.
Конечно, не стоит ожидать чудес от сервиса, который вообще не предназначен для автодополнения адреса, но все же резюмирую:
Надежный источник данных
Удобный способ запроса/доставки данных (запрос обычным GETом, обратно — JSON)
Возможно автодополнение одной строкой и даже разбивка полученных данных по компонентам (Страна, регион, город, улица, дом)
Тяжело ограничить область поиска
Сервис не предназначен для автодополнения
Google Autocomplete (Google Places API)
С Google Autocomplete у меня с самого начала не срослось: если запрашивать информацию обычным GETом, то гугловский сервер отвечает ошибкой CORS (Origin… is not allowed by Access-Control-Allow-Origin), а JSONP они не поддерживают после выхода третьей версией API. Некоторые говорят, что это сделано специально, чтобы в веб-разработке использовали их JS библиотеку. Конечно, можно еще сделать прокси, через который будут проходить данные, но я решил не заморачиваться ради такой мелочи.
Но для объективности сравнения, я все же попробовал Google Autocomplete через JS библиотеку. В итоге:
Надежный источник данных
Возможно автодополнение одной строкой
Легко подключить (если использовать их JS библиотеку)
Невозможно достучаться до API с фронтенда из-за CORS
Нельзя строго ограничить область поиска до одного города (Можно строго ограничить только страну, или нестрого ограничить с помощью параметра ‘bounds’)
КЛАДР в облаке
КЛАДР в облаке — отечественный сервис, который не раз упоминали на хабре.
Лично для меня он оказался неподходящим, т.к. не позволяет производить автодополнение одной строкой. Вы можете искать или регионы, или города, или улицы, или номера домов, но никак не всё это вместе в одной строке. То есть или придется разбивать одну форму на несколько, или искать только по названиям улиц только в Москве.
Мне это не подходит, но сильные и слабые стороны я всё же приведу:
Авторитетный источник данных (КЛАДР)
Постоянные обновления базы данных
Российский разработчик
Хороший API
Открытый исходный код
Невозможно автодополнение одной строкой
DaData подсказки
Я уже отчаялся найти сервис своей мечты и собирался вернуться к Google Geocode, как вспомнил про подсказки сервиса DaData.
Сразу перейду к сравнению:
Возможно автодополнение одной строкой
При начале ввода первых букв улицы, он сразу предлагает и номера домов на этой улице
Российский разработчик
Разбивка полученных данных по компонентам (даже индекс и код КЛАДР и ОКАТО)
Неизвестная база данных
Бесплатным пользователям не гарантируется стопроцентный uptime
Неочевидный формат запроса данных (POST, а не GET)
Скудный API
+ БОНУС: автодополнение еще и имён.
В итоге лично я решил остановиться на последнем варианте, заодно и воспользоваться их автодополнением имён. Правда я считаю, что у каждого свои задачи, и для каждой конкретной задачи нужен свой инструмент.
Places Autocomplete Service
AutocompleteService class
Contains methods related to retrieving Autocomplete predictions.
Requires the &libraries=places URL parameter. See Libraries in the Maps JavaScript API.
Constructor
Methods
AutocompletionRequest interface
Requires the &libraries=places URL parameter. See Libraries in the Maps JavaScript API.
Properties
AutocompleteResponse class
An Autocomplete response returned by the call to AutocompleteService.getPlacePredictions containing a list of AutocompletePrediction s.
Requires the &libraries=places URL parameter. See Libraries in the Maps JavaScript API.
Properties
QueryAutocompletionRequest interface
Requires the &libraries=places URL parameter. See Libraries in the Maps JavaScript API.
Properties
AutocompleteSessionToken class
Represents a session token used for tracking an autocomplete session, which can be a series of AutocompleteService.getPlacePredictions calls followed by a single PlacesService.getDetails call.
Requires the &libraries=places URL parameter. See Libraries in the Maps JavaScript API.
Constructor
ComponentRestrictions interface
Defines the component restrictions that can be used with the autocomplete service.
Requires the &libraries=places URL parameter. See Libraries in the Maps JavaScript API.
Properties
AutocompletePrediction interface
Represents a single autocomplete prediction.
Requires the &libraries=places URL parameter. See Libraries in the Maps JavaScript API.
Properties
QueryAutocompletePrediction interface
Represents a single Query Autocomplete prediction.
Requires the &libraries=places URL parameter. See Libraries in the Maps JavaScript API.
Properties
PredictionTerm interface
Represents a prediction term.
Requires the &libraries=places URL parameter. See Libraries in the Maps JavaScript API.
Properties
PredictionSubstring interface
Represents a prediction substring.
Requires the &libraries=places URL parameter. See Libraries in the Maps JavaScript API.
Properties
StructuredFormatting interface
Contains structured information about the place’s description, divided into a main text and a secondary text, including an array of matched substrings from the autocomplete input, identified by an offset and a length, expressed in unicode characters.
Requires the &libraries=places URL parameter. See Libraries in the Maps JavaScript API.
Properties
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Places Autocomplete
This page describes the client-side library available with the Maps JavaScript API. If you want to work with the Places API web service on your server, take a look at the Node.js Client for Google Maps Services. The page at that link also introduces the Java Client, Python Client and Go Client for Google Maps Services.
Introduction
Autocomplete is a feature of the Places library in the Maps JavaScript API. You can use autocomplete to give your applications the type-ahead-search behavior of the Google Maps search field. The autocomplete service can match on full words and substrings, resolving place names, addresses, and plus codes. Applications can therefore send queries as the user types, to provide on-the-fly place predictions.
Getting started
Before using the Places library in the Maps JavaScript API, first ensure that the Places API is enabled in the Google Cloud Console, in the same project you set up for the Maps JavaScript API.
To view your list of enabled APIs:
Loading the library
The Places service is a self-contained library, separate from the main Maps JavaScript API code. To use the functionality contained within this library, you must first load it using the libraries parameter in the Maps API bootstrap URL:
See the Libraries Overview for more information.
Summary of classes
The API offers two types of autocomplete widgets, which you can add via the Autocomplete and SearchBox classes respectively. In addition, you can use the AutocompleteService class to retrieve autocomplete results programmatically (see the Maps JavaScript API Reference: AutocompleteService class).
Below is a summary of the classes available:
Adding an Autocomplete widget
The Autocomplete widget creates a text input field on your web page, supplies predictions of places in a UI pick list, and returns place details in response to a getPlace() request. Each entry in the pick list corresponds to a single place (as defined by the Places API).
The Autocomplete constructor takes two arguments:
Note: If you receive unexpected results with a country code, verify that you are using a code which includes the countries, dependent territories, and special areas of geographical interest you intend. You can find code information at Wikipedia: List of ISO 3166 country codes or the ISO Online Browsing Platform.
Constraining Autocomplete predictions
By default, Place Autocomplete presents all place types, biased for predictions near the user’s location, and fetches all available data fields for the user’s selected place. Set Place Autocomplete options to present more relevant predictions based on your use case.
Set options at construction
Call setOptions() to change an option’s value for an existing widget.
TypeScript
JavaScript
Specify data fields
Specify data fields to avoid being billed for Places Data SKUs you don’t need. Include the fields property in the AutocompleteOptions that are passed to the widget constructor, as demonstrated in the previous example, or call setFields() on an existing Autocomplete object.
Define biases and search-area boundaries for Autocomplete
You can bias the autocomplete results to favor an approximate location or area, in the following ways:
The previous example demonstrates setting bounds at creation. The following examples demonstrate the other biasing techniques.
Change the bounds of an existing Autocomplete
Call setBounds() to change the search area on an existing Autocomplete to rectangular bounds.
TypeScript
JavaScript
Set the bounds to the map’s viewport
Use bindTo() to bias the results to the map’s viewport, even while that viewport changes.
TypeScript
JavaScript
Use unbind() to unbind the Autocomplete predictions from the map’s viewport.
TypeScript
JavaScript
Restrict the search to the current bounds
Set the strictBounds option to restrict the results to the current bounds, whether based on map viewport or rectangular bounds.
Restrict predictions to a specific country
Use the componentRestrictions option or call setComponentRestrictions() to restrict the autocomplete search to a specific set of up to five countries.
TypeScript
JavaScript
Constrain place types
Use the types option or call setTypes() to restrict predictions to certain place types. The Places Autocomplete demo demonstrates the differences in predictions between different place types. See types supported in place autocomplete requests for an explanation of supported values for this property.
Getting place information
When a user selects a place from the predictions attached to the autocomplete text field, the service fires a place_changed event. To get place details:
By default, when a user selects a place, autocomplete returns all of the available data fields for the selected place, and you will be billed accordingly. Use Autocomplete.setFields() to specify which place data fields to return. Read more about the PlaceResult object, including a list of place data fields that you can request. To avoid paying for data that you don’t need, be sure to use Autocomplete.setFields() to specify only the place data that you will use.
The name property contains the description from Places Autocomplete predictions. You can read more about the description in the Places Autocomplete documentation.
For address forms, it is useful to get the address in structured format. To return the structured address for the selected place, call Autocomplete.setFields() and specify the address_components field.
The following example uses autocomplete to fill the fields in an address form.
TypeScript
JavaScript
Customizing placeholder text
By default, the text field created by the autocomplete service contains standard placeholder text. To modify the text, set the placeholder attribute on the input element:
Note: The default placeholder text is localized automatically. If you specify your own placeholder value, you must handle the localization of that value in your application. For information on how the Google Maps JavaScript API chooses the language to use, please read the documentation on localization.
Adding a SearchBox widget
The SearchBox allows users to perform a text-based geographic search, such as ‘pizza in New York’ or ‘shoe stores near robson street’. You can attach the SearchBox to a text field and, as text is entered, the service will return predictions in the form of a drop-down pick list.
SearchBox supplies an extended list of predictions, which can include places (as defined by the Places API) plus suggested search terms. For example, if the user enters ‘pizza in new’, the pick list may include the phrase ‘pizza in New York, NY’ as well as the names of various pizza outlets. When a user selects a place from the list, information about that place is returned to the SearchBox object, and can be retrieved by your application.
The SearchBox constructor takes two arguments:
The following code uses the bounds parameter to bias the results towards places within a particular geographic area, specified via laitude/longitude coordinates.
Changing the search area for SearchBox
Getting place information
When the user selects an item from the predictions attached to the search box, the service fires a places_changed event. You can call getPlaces() on the SearchBox object, to retrieve an array containing several predictions, each of which is a PlaceResult object.
For more information about the PlaceResult object, refer to the documentation on place detail results.
TypeScript
JavaScript
Programmatically retrieving Place Autocomplete Service predictions
To retrieve predictions programmatically, use the AutocompleteService class. AutocompleteService does not add any UI controls. Instead, it returns an array of prediction objects, each containing the text of the prediction, reference information, and details of how the result matches the user input. This is useful if you want more control over the user interface than is offered by the Autocomplete and SearchBox described above.
AutocompleteService exposes the following methods:
Both of the above methods return an array of prediction objects of the following form:
The example below executes a query prediction request for the phrase ‘pizza near’ and displays the result in a list.
Попытка автоматического завершения работы моего приложения Google Maps.
К сожалению, ничего не происходит при наборе адреса.
Изменить: я на самом деле получаю следующую ошибку:
Uncaught TypeError: Невозможно прочитать свойство ‘autocomplete’ из неопределенного
Не уверен, почему, код помещен в мою функцию инициализации карты.
Редактировать 2: исправлено. Ответ ниже.
7 ответов
Исправлена. Библиотека автозаполнения на самом деле является отдельной библиотекой, которая должна быть явно загружена. Следующая строка решила проблему.
Вариант обратного вызова также работает (с определенной функцией initMap):
Это похоже на другой SO ответ и не согласуется с официальная документация (если только не предоставлено key в URL-адресе).
Вы должны добавить ‘defer async’ к атрибуту скрипта, например так:
Я обнаружил эту ошибку, потому что мой ключ API превысил суточную квоту запросов для этого API.
Я просто создаю новый ключ API и заменяю его вместо старого.
Ваше исправление сработало и для меня. Я использую подключаемый модуль jQuery Geocomplete http://ubilabs.github.com/geocomplete/ и инструкции на их домашней странице говорят, чтобы использовать это
Но это не сработало для меня и получало ту же ошибку.
Поскольку этот вопрос помог мне, я решил, что помогу всем, у кого эта проблема возникла в 2019 году. В 2019 году вы добавляете импорт API Google Maps следующим образом:
Затем добавьте & библиотеки = места до конца, чтобы все сказанное и сделанное выглядело так:




