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 theNode.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, andplus codes. Applications can therefore send queries as the user types, to provide on-the-fly place predictions. As defined by the Places API, a 'place' can be an establishment, a geographic location, or a prominent point of interest.
Getting started
Before using the Places library in the Maps JavaScript API, first verify that the Places API is enabled in the Google Cloud console, in the same project you set up for the Maps JavaScript API.
Click theSelect a project button, then select the same project you set up for the Maps JavaScript API and clickOpen.
From the list of APIs on theDashboard, look forPlaces API.
If you see the API in the list, you're all set. However, this project is in Legacy status. For more information about the Legacy stage and how to migrate from Legacy to newer services, seeLegacy products and features. An exception is available for theAutocomplete andSearchBox widgets, which are not yet available as a GA product on the Places API (New).
Load the library
The Places service is a self-contained library, separate from the main Maps JavaScript API code. To use the features contained within this library, you must first load it using thelibraries parameter in the Maps API bootstrap URL:
The API offers two types of autocomplete widgets, which you can add using theAutocomplete andSearchBox classes respectively. In addition, you can use theAutocompleteService class to retrieve autocomplete results programmatically (see the Maps JavaScript API Reference:AutocompleteService class).
Below is a summary of the classes available:
Autocomplete adds a text input field to your web page, and monitors that field for character entries. As the user enters text, autocomplete returns place predictions in the form of a drop-down list. When the user selects a place from the list, information about the place is returned to the autocomplete object, and can be retrieved by your application. See the detailsbelow.Figure 1: Autocomplete text field and pick listFigure 2: Completed address form
SearchBox adds a text input field to your web page, in much the same way asAutocomplete. The differences are as follows:
The main difference lies in the results that appear in the 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.
SearchBox offers fewer options thanAutocomplete for restricting the search. In the former, you can bias the search towards a givenLatLngBounds. In the latter, you can restrict the search to a particular country and particular place types, as well as setting the bounds. For more information, seebelow.
Figure 3: A SearchBox presents search terms and place predictions. See the detailsbelow.
You can create anAutocompleteService object to retrieve predictions programmatically. CallgetPlacePredictions() to retrieve matching places, or callgetQueryPredictions() to retrieve matching places plus suggested search terms. Note:AutocompleteService does not add any UI controls. Instead, the above methods return an array of prediction objects. Each prediction object contains the text of the prediction, as well as reference information and details of how the result matches the user input. See the detailsbelow.
TheAutocompletewidget creates a text input field on your web page, supplies predictions of places in a UI picklist, and returns place details in response to agetPlace() request. Each entry in thepick list corresponds to a single place (as defined by the Places API).
TheAutocomplete constructor takes two arguments:
An HTMLinput element of typetext. This is the input field that the autocompleteservice will monitor and attach its results to.
An optionalAutocompleteOptions argument, which cancontain the following properties:
An array of datafields to be included inthePlace Details response for the user's selectedPlaceResult. If theproperty is not set or if['ALL'] is passed in, all available fields are returned andbilled for (this is not recommendedfor production deployments). For a list of fields, seePlaceResult.
An array oftypes thatspecifies an explicit type or a type collection, as listed in thesupported types. If no type is specified, all types arereturned.
bounds is agoogle.maps.LatLngBounds object specifyingthe area in which to search for places. The results are biased towards, but not restricted to,places contained within these bounds.
componentRestrictions can be used to restrict results tospecific groups. You can usecomponentRestrictions to filter by up to 5countries. Countries must be passed as as a two-character, ISO 3166-1 Alpha-2 compatible countrycode. Multiple countries must be passed as a list of country codes.
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 atWikipedia: List of ISO 3166 country codes or theISO Online Browsing Platform.
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
TheAutocomplete constructor accepts anAutocompleteOptions parameter to set constraints at widget creation. The following example sets thebounds,componentRestrictions, andtypes options to requestestablishment type places, favoring those within the specified geographic area and restricting predictions to only places within the United States. Setting thefields option specifies what information to return about the user's selected place.
CallsetOptions() to change an option's value for an existing widget.
TypeScript
constcenter={lat:50.064192,lng:-130.605469};// Create a bounding box with sides ~10km away from the center pointconstdefaultBounds={north:center.lat+0.1,south:center.lat-0.1,east:center.lng+0.1,west:center.lng-0.1,};constinput=document.getElementById("pac-input")asHTMLInputElement;constoptions={bounds:defaultBounds,componentRestrictions:{country:"us"},fields:["address_components","geometry","icon","name"],strictBounds:false,};constautocomplete=newgoogle.maps.places.Autocomplete(input,options);
constcenter={lat:50.064192,lng:-130.605469};// Create a bounding box with sides ~10km away from the center pointconstdefaultBounds={north:center.lat+0.1,south:center.lat-0.1,east:center.lng+0.1,west:center.lng-0.1,};constinput=document.getElementById("pac-input");constoptions={bounds:defaultBounds,componentRestrictions:{country:"us"},fields:["address_components","geometry","icon","name"],strictBounds:false,};constautocomplete=newgoogle.maps.places.Autocomplete(input,options);
Specify data fields to avoid being billed forPlaces Data SKUs you don't need. Include thefields property in theAutocompleteOptions that are passed to the widget constructor, as demonstrated in the previousexample, or callsetFields() on an existingAutocomplete object.
Use thetypes option or callsetTypes() to constrainpredictions to certain place types. This constraint specifies a type or a type collection,as listed inPlace Types.If no constraint is specified, all types are returned.
For the value of thetypes option or the value passed tosetTypes(), youcan specify either:
When a user selects a place from the predictions attached to the autocomplete text field, the service fires aplace_changed event. To get place details:
Create an event handler for theplace_changed event, and calladdListener() on theAutocomplete object to add the handler.
CallAutocomplete.getPlace() on theAutocomplete object, to retrieve aPlaceResult object, which you can then use to get more information about the selected place.
By default, when a user selects a place, autocomplete returns all of the available data fields for the selected place, and you will bebilled accordingly. UseAutocomplete.setFields() to specify which place data fields to return. Read more about thePlaceResult 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 useAutocomplete.setFields() to specify only the place data that you will use.
Thename property contains thedescription from Places Autocomplete predictions. You can read more about thedescription in thePlaces Autocomplete documentation.
For address forms, it is useful to get the address in structured format. To return the structured address for the selected place, callAutocomplete.setFields() and specify theaddress_components field.
The following example uses autocomplete to fill the fields in an addressform.
TypeScript
functionfillInAddress(){// Get the place details from the autocomplete object.constplace=autocomplete.getPlace();letaddress1="";letpostcode="";// Get each component of the address from the place details,// and then fill-in the corresponding field on the form.// place.address_components are google.maps.GeocoderAddressComponent objects// which are documented at http://goo.gle/3l5i5Mrfor(constcomponentofplace.address_componentsasgoogle.maps.GeocoderAddressComponent[]){// @ts-ignore remove once typings fixedconstcomponentType=component.types[0];switch(componentType){case"street_number":{address1=`${component.long_name}${address1}`;break;}case"route":{address1+=component.short_name;break;}case"postal_code":{postcode=`${component.long_name}${postcode}`;break;}case"postal_code_suffix":{postcode=`${postcode}-${component.long_name}`;break;}case"locality":(document.querySelector("#locality")asHTMLInputElement).value=component.long_name;break;case"administrative_area_level_1":{(document.querySelector("#state")asHTMLInputElement).value=component.short_name;break;}case"country":(document.querySelector("#country")asHTMLInputElement).value=component.long_name;break;}}address1Field.value=address1;postalField.value=postcode;// After filling the form with address components from the Autocomplete// prediction, set cursor focus on the second address line to encourage// entry of subpremise information such as apartment, unit, or floor number.address2Field.focus();}
functionfillInAddress(){// Get the place details from the autocomplete object.constplace=autocomplete.getPlace();letaddress1="";letpostcode="";// Get each component of the address from the place details,// and then fill-in the corresponding field on the form.// place.address_components are google.maps.GeocoderAddressComponent objects// which are documented at http://goo.gle/3l5i5Mrfor(constcomponentofplace.address_components){// @ts-ignore remove once typings fixedconstcomponentType=component.types[0];switch(componentType){case"street_number":{address1=`${component.long_name}${address1}`;break;}case"route":{address1+=component.short_name;break;}case"postal_code":{postcode=`${component.long_name}${postcode}`;break;}case"postal_code_suffix":{postcode=`${postcode}-${component.long_name}`;break;}case"locality":document.querySelector("#locality").value=component.long_name;break;case"administrative_area_level_1":{document.querySelector("#state").value=component.short_name;break;}case"country":document.querySelector("#country").value=component.long_name;break;}}address1Field.value=address1;postalField.value=postcode;// After filling the form with address components from the Autocomplete// prediction, set cursor focus on the second address line to encourage// entry of subpremise information such as apartment, unit, or floor number.address2Field.focus();}window.initAutocomplete=initAutocomplete;
TheSearchBox allows users to perform a text-based geographic search, such as 'pizza in New York' or 'shoe stores near robson street'. You can attach theSearchBox 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.
When the user selects an item from the predictions attached to the search box, the service fires aplaces_changed event. You can callgetPlaces() on theSearchBox object, to retrieve an array containing several predictions, each of which is aPlaceResult object.
For more information about thePlaceResult object, refer to the documentation on place detail results.
TypeScript
// Listen for the event fired when the user selects a prediction and retrieve// more details for that place.searchBox.addListener("places_changed",()=>{constplaces=searchBox.getPlaces();if(places.length==0){return;}// Clear out the old markers.markers.forEach((marker)=>{marker.setMap(null);});markers=[];// For each place, get the icon, name and location.constbounds=newgoogle.maps.LatLngBounds();places.forEach((place)=>{if(!place.geometry||!place.geometry.location){console.log("Returned place contains no geometry");return;}consticon={url:place.iconasstring,size:newgoogle.maps.Size(71,71),origin:newgoogle.maps.Point(0,0),anchor:newgoogle.maps.Point(17,34),scaledSize:newgoogle.maps.Size(25,25),};// Create a marker for each place.markers.push(newgoogle.maps.Marker({map,icon,title:place.name,position:place.geometry.location,}));if(place.geometry.viewport){// Only geocodes have viewport.bounds.union(place.geometry.viewport);}else{bounds.extend(place.geometry.location);}});map.fitBounds(bounds);});
// Listen for the event fired when the user selects a prediction and retrieve// more details for that place.searchBox.addListener("places_changed",()=>{constplaces=searchBox.getPlaces();if(places.length==0){return;}// Clear out the old markers.markers.forEach((marker)=>{marker.setMap(null);});markers=[];// For each place, get the icon, name and location.constbounds=newgoogle.maps.LatLngBounds();places.forEach((place)=>{if(!place.geometry||!place.geometry.location){console.log("Returned place contains no geometry");return;}consticon={url:place.icon,size:newgoogle.maps.Size(71,71),origin:newgoogle.maps.Point(0,0),anchor:newgoogle.maps.Point(17,34),scaledSize:newgoogle.maps.Size(25,25),};// Create a marker for each place.markers.push(newgoogle.maps.Marker({map,icon,title:place.name,position:place.geometry.location,}),);if(place.geometry.viewport){// Only geocodes have viewport.bounds.union(place.geometry.viewport);}else{bounds.extend(place.geometry.location);}});map.fitBounds(bounds);});
Programmatically retrieving Place Autocomplete Service predictions
To retrieve predictions programmatically, use theAutocompleteService 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 theAutocomplete andSearchBox described above.
AutocompleteService exposes the following methods:
getPlacePredictions() returns place predictions. Note: A 'place' can be an establishment, geographic location, or prominent point of interest, as defined by the Places API.
getQueryPredictions() returns 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.
Both of the above methods return an array ofprediction objects of the following form:
description is the matched prediction.
distance_meters is the distance in meters of the place from the specifiedAutocompletionRequest.origin.
matched_substrings contains a set of substrings in the description that match elements in the user's input. This is useful for highlighting those substrings in your application. In many cases, the query will appear as a substring of the description field.
length is the length of the substring.
offset is the character offset, measured from the beginning of the description string, at which the matched substring appears.
place_id is a textual identifier that uniquely identifies a place. To retrieve information about the place, pass this identifier in theplaceId field of aPlace Details request. Learn more about how toreference a place with a place ID.
terms is an array containing elements of the query. For a place, each element will typically make up a portion of the address.
offset is the character offset, measured from the beginning of the description string, at which the matched substring appears.
value is the matching term.
The example below executes a query prediction request for the phrase 'pizza near' and displays the result in a list.
TypeScript
// This example retrieves autocomplete predictions programmatically from the// autocomplete service, and displays them as an HTML list.// This example requires the Places library. Include the libraries=places// parameter when you first load the API. For example:// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">functioninitService():void{constdisplaySuggestions=function(predictions:google.maps.places.QueryAutocompletePrediction[]|null,status:google.maps.places.PlacesServiceStatus){if(status!=google.maps.places.PlacesServiceStatus.OK||!predictions){alert(status);return;}predictions.forEach((prediction)=>{constli=document.createElement("li");li.appendChild(document.createTextNode(prediction.description));(document.getElementById("results")asHTMLUListElement).appendChild(li);});};constservice=newgoogle.maps.places.AutocompleteService();service.getQueryPredictions({input:"pizza near Syd"},displaySuggestions);}declareglobal{interfaceWindow{initService:()=>void;}}window.initService=initService;
// This example retrieves autocomplete predictions programmatically from the// autocomplete service, and displays them as an HTML list.// This example requires the Places library. Include the libraries=places// parameter when you first load the API. For example:// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">functioninitService(){constdisplaySuggestions=function(predictions,status){if(status!=google.maps.places.PlacesServiceStatus.OK||!predictions){alert(status);return;}predictions.forEach((prediction)=>{constli=document.createElement("li");li.appendChild(document.createTextNode(prediction.description));document.getElementById("results").appendChild(li);});};constservice=newgoogle.maps.places.AutocompleteService();service.getQueryPredictions({input:"pizza near Syd"},displaySuggestions);}window.initService=initService;
<html> <head> <title>Retrieving Autocomplete Predictions</title> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <p>Query suggestions for 'pizza near Syd':</p> <ul></ul> <!-- Replace Powered By Google image src with self hosted image. https://developers.google.com/maps/documentation/places/web-service/policies#other_attribution_requirements --> <img src="https://storage.googleapis.com/geo-devrel-public-buckets/powered_by_google_on_white.png" alt="Powered by Google" /> <!-- The `defer` attribute causes the script to execute after the full HTML document has been parsed. For non-blocking uses, avoiding race conditions, and consistent behavior across browsers, consider loading using Promises. See https://developers.google.com/maps/documentation/javascript/load-maps-js-api for more information. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initService&libraries=places&v=weekly" defer ></script> </body></html>
AutocompleteService.getPlacePredictions()can use session tokens(if implemented) to group together autocomplete requests for billingpurposes. Session tokens group the query and selection phases of a userautocomplete search into a discrete session for billing purposes. The sessionbegins when the user starts typing a query, and concludes when they select aplace. Each session can have multiple queries, followed by one place selection.Once a session has concluded, the token is no longer valid. Your app mustgenerate a fresh token for each session. We recommend using session tokens forall autocomplete sessions. If thesessionToken parameter isomitted, or if you reuse a session token, the session is charged as if nosession token was provided (each request is billed separately).
You can use the same session token to make a singlePlace Detailsrequest on the place that results from a call toAutocompleteService.getPlacePredictions().In this case, the autocomplete request is combined with the Place Detailsrequest, and the call is charged as a regular Place Details request. There is no charge for theautocomplete request.
Be sure to pass a unique session token for each new session. Using the same token for more than one Autocomplete session will invalidate those Autocomplete sessions, and all Autocomplete request in the invalid sessions will be charged individually usingAutocomplete Per Request SKU.Read more about session tokens.
The following example shows creating a session token, then passing it in anAutocompleteService (thedisplaySuggestions()function has been omitted for brevity):
// Create a new session token.varsessionToken=newgoogle.maps.places.AutocompleteSessionToken();// Pass the token to the autocomplete service.varautocompleteService=newgoogle.maps.places.AutocompleteService();autocompleteService.getPlacePredictions({input:'pizza near Syd',sessionToken:sessionToken},displaySuggestions);
Be sure to pass a unique session token for each new session. Using the sametoken for more than one session will result in each request being billedindividually.
By default, the UI elements provided byAutocomplete andSearchBox are styled for inclusion on a Google map. You may want to adjust the styling to suit your own site. The following CSS classes are available. All classes listed below apply to both theAutocomplete and theSearchBox widgets.
CSS classes for Autocomplete and SearchBox widgets
CSS class
Description
pac-container
The visual element containing the list of predictions returned by the Place Autocomplete service. This list appears as a drop-down list below theAutocomplete orSearchBox widget.
pac-icon
The icon displayed to the left of each item in the list of predictions.
pac-item
An item in the list of predictions supplied by theAutocomplete orSearchBox widget.
pac-item:hover
The item when the user hovers their mouse pointer over it.
pac-item-selected
The item when the user selects it using the keyboard. Note: Selected items will be a member of this class and of thepac-item class.
pac-item-query
A span inside apac-item that is the main part of the prediction. For geographic locations, this contains a place name, like 'Sydney', or a street name and number, like '10 King Street'. For text-based searches such as 'pizza in New York', it contains the full text of the query. By default, thepac-item-query is colored black. If there is any additional text in thepac-item, it is outsidepac-item-query and inherits its styling frompac-item. It is colored gray by default. The additional text is typically an address.
pac-matched
The part of the returned prediction that matches the user's input. By default, this matched text is highlighted in bold text. Note that the matched text may be anywhere withinpac-item. It is not necessarily part ofpac-item-query, and it could be partly withinpac-item-query as well as partly in the remaining text inpac-item.
Place Autocomplete (Legacy) optimization
This section describes best practices to help you make the most of the Place Autocomplete (Legacy) service.
Develop an understanding of essential Place Autocomplete (Legacy)data fields from the start.
Location biasing and location restriction fields are optional but can have a significant impact on autocomplete performance.
Use error handling to make sure your app degrades gracefully if the API returns an error.
Make sure your app handles when there is no selection and offers users a way to continue.
Cost optimization best practices
Basic cost optimization
To optimize the cost of using the Place Autocomplete (Legacy) service, use field masks in Place Details (Legacy) and Place Autocomplete (Legacy) widgets to return only theplace data fields you need.
Advanced cost optimization
Consider programmatic implementation of Place Autocomplete (Legacy) in order to accessPer Request pricing and requestGeocoding API results about the selected place instead of Place Details (Legacy). Per Request pricing paired with Geocoding API is more cost-effective than Per Session (session-based) pricing if both of the following conditions are met:
If you only need the latitude/longitude or address of the user's selected place, the Geocoding API delivers this information for less than a Place Details (Legacy) call.
If users select an autocomplete prediction within an average of four Place Autocomplete (Legacy) predictions requests or fewer, Per Request pricing may be more cost-effective than Per Session pricing.
For help selecting the Place Autocomplete (Legacy) implementation that fits your needs, select the tab that corresponds to your answer to the following question.
Does your application require any information other than the address and latitude/longitude of the selected prediction?
The following guidelines describe ways to optimize Place Autocomplete (Legacy) performance:
Add country restrictions,location biasing, and (for programmatic implementations) language preference to your Place Autocomplete (Legacy) implementation. Language preference is not needed with widgets since they pick language preferences from the user's browser or mobile device.
If Place Autocomplete (Legacy) is accompanied by a map, you can bias location by map viewport.
In situations when a user does not choose one of the Place Autocomplete (Legacy) predictions, generally because none of those predictions are the result-address wanted, you can reuse the original user input to attempt to get more relevant results:
If you expect the user to enter only address information, reuse the original user input in a call to theGeocoding API.
If you expect the user to enter queries for a specific place by name or address, use aFind Place (Legacy) request. If results are only expected in a specific region, uselocation biasing.
Other scenarios when it's best to fall back to the Geocoding API include:
Users inputting subpremise addresses, such as addresses for specific units or apartments within a building. For example, the Czech address "Stroupežnického 3191/17, Praha" yields a partial prediction in Place Autocomplete (Legacy).
Users inputting addresses with road-segment prefixes like "23-30 29th St, Queens" in New York City or "47-380 Kamehameha Hwy, Kaneohe" on the island of Kauai in Hawai'i.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-10-31 UTC."],[],[]]