Google Map Place Autocomplete API
Google Map (Places and Place Details) - Autocomplete API Documentation
Standard Pricing
In 2017 & 2018 Google changed the pricing of their APIs. Part of the API is with a subscription to the Google Cloud Platform, which is $200 / mo and you get free credit of $200 / mo, plus a the first X amount of each different API request free/included.
With the change, there is much to be done.
Setup
There is a couple ways to go about this depending on your need.
There is a way for Android, and a different way for iOS as well as a way for WebServices (mostly back-end connections), and Javascript front-end connections.
They aren’t that different, but each method is customized to how tyou make a web api call, and in the case of the front-end Javascript option, what you do with it.
This is the basic code that I have for a page. Just the HTML object which is an input type="text"
, and the javascript includes. Some of this was changed for brevity of the example and some was excluded for proprietary reasons, and other things were added just for examples. There is some really complex things that can be done with this, but this is a basic “search for address” box that will autocomplete a list of potential places in a dropdown as you start typing.
<!--
header and more
.....
body
....
form
....
-->
<div class="searchField">
<input id="searchLocation" name="searchLocation" type="text" placeholder="Enter an Address">
</div>
<!-- more code.... -->
<!-- footer -->
<script>
// initiate search area for autocomplete of places from Google Maps Street Addresses
function initAutocomplete() {
// define the search location box
var searchBox = $("#searchLocation")[0];
// define the options
// get center point of all stores and create bounds for search bias
// **OPTIONAL** - This specifically is for BIASING and I wanted the BIAS to be towards the middle of the grouping of stores we have, there are other ways to do this, this is just an example
var storeListCenter = getCenterStoreLocations();
var centerStoreArea = new google.maps.LatLng(storeListCenter.MIDLAT, storeListCenter.MIDLNG);
var centerAutoCompSearch = new google.maps.LatLngBounds(centerStoreArea);
var options = {
bounds: centerAutoCompSearch
};
// initiate the autocomplete with the options on the search box
var autocomplete = new google.maps.places.Autocomplete(searchBox, options);
// add function to submit form on location selection
// **OPTIONAL** - I have some additional functionality when a user selects something from the autocomplete dropdown
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
onSelectSearchLocation(place);
});
};
</script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places®ion=ca&language=en&key=[YOUR_API_KEY]&callback=initAutocomplete" async defer></script>
First I want to clear something up. There is always a few ways to do things. This is how I did it for my purposes. You can add the Google Map Places API library before the script and then initiate the object on page ready or something. I did mine with a callback, and I want to talk about the API url string.
Second, I want you to know that what the above way is, is a common way, and its using the “Autocomplete Widget”. Anytime, you are doing the new google.maps.places.Autocomplete()
instead of AutocompleteServices
or something else, you are using the “Autocomplete Widget”. More on this later.
I wanted mine to be defered and async so the page loads fully first, possibly making it faster, and then it tries to download the library and initate the object. In my scenario, this makes things faster, but that is not aways the case.
If you are using the API as part of front-end javascript, you must include this API url. Lets go through it. NOTE: The order of the URL parameters doesn’t matter, and this is as of 12/2018. Google notes in their documentation that a few things have been depracted and won’t make the call work anymore, such as addint a `` parameter.
https://maps.googleapis.com/maps/api/js?libraries=places®ion=ca&language=en&key=[YOUR_API_KEY]&callback=initAutocomplete
Base = https://maps.googleapis.com/maps/api/js?libraries=places
This is the base for most google map api calls. The “libraries” parameter in the URL will change depending on what you are looking for. This specific one is for the “places” which has the AutoComplete feature and more. This will also slighty change if you are doing a webservice vs iOS vs Android and such, but this is focusing on front-end Javascript.
Key = &key=[YOUR_API_KEY]
The key is something you would get from your Google Cloud account and would restrict it to only be used in certain domains and such. See the billing page for Google for this and sign up for an account.
REGION = ®ion=ca
This is not a restriction, but a bias. There is additional “biasing” you can do in the Javascript, but this will/could set it to be the country code of your choice. Also, the results of the autocomplete WILL NOT show the country in the address if it matches this region.
Language = &language=en
This is the 2 character language notation that the results will be returned in. Leave it blank (don’t pass this parameter at all) if you want the user to see results in the native language of their browser.
Callback = &callback=initAutocomplete
This is a function that then utilizes the code. As standard Javascript functionality, you have to have that function declared before you call this script with the callback. If you just want the object to be initiated on document ready, then remove this parameter, call the URL first and then put the “initialization” in the document on ready function.
According to the Google Docs () https://developers.google.com/maps/documentation/javascript/places-autocomplete
Warning: Be sure to pass a unique session token for each new session. Using the same token for more than one session will result in each request being billed individually. Note that the Autocomplete Widget handles sessions automatically (you don't need to do anything additional).
Now, lets dive into the basic Javascript example.
Session Token Clarification
According to the Google Docs (all the way at the bottom of the page in a “warning text”)… https://developers.google.com/maps/documentation/javascript/places-autocomplete
Warning: Be sure to pass a unique session token for each new session. Using the same token for more than one session will result in each request being billed individually. Note that the Autocomplete Widget handles sessions automatically (you don't need to do anything additional).
Now, lets dive into the basic Javascript example.
This may be a bit confusing, only because you are trying to get into the nomenclature of the google docs and what these things and possibly because you were doing it one way and suddenly your boss or client or someone else ask you to use Sessions/Session Tokens instead.
If you do new google.maps.places.Autocomplete()
instead of AutocompleteServices
or something along those lines, you are using the “Autocomplete Widget”.
The autocomplete widget will handle the session / session tokens itself.
Prove it!
I trust google and google docs, but there was plenty of confusion on the web about this. So I wanted proof, besides getting a bill after a month. FYI - the billing in Google Clound Platform Console (https://console.cloud.google.com/google/maps-apis?pli=1) will show you this almost right away and will corroborate the stuff below and above.
Looking at the Network activity in Dev Tools, we see that there is a few calls to the Autocomplete Service.
I did not use the “AutocompleteService” function here, this is a basic example setup the same way I have listed above for the Callback with using the “Autocomplete Widget” via new google.maps.places.Autocomplete()
.
When you go to the page, you can see the call to library first, first screenshot of Dev Tools below.
Next I did a search, which worked. I started to type in a basic address of 1990, you can see 4 request made to the API after that. 1 request/call for each character I type in. Each of these request names begin with “AutocompleteServices.GetPredictions…”, even though I DID NOT USE AutocompleteServices in my code. On the back-end, the “Autocomplete Widget” is using the “AutocompeleteServices” and doing all the UI/UX work for you as well as the functionality and the session and tokens. These are in the Dev tools screenshots 1-3 below.
Then you see a 5th request call to “PlaceServces.GetPlaceDetails”, which was when I selected from the dropdown. This is the dev tools screenshot 4 below.
Looking at the headers, for each of these requests, I see a few things.
The first thing, circled at the bottom is a “token”. I know I just said and Google Docs just said that the “Autocomplete Widget” handles the session token, and a keen eye will see that this “token” value is different for every request. It is also not in ‘version 4 UUID’ format, which is recommended by Google, but that is a different topic. This “token” in the header, IS NOT the session token. This is buried in documentation that is 5 years old for a previous version of this on Google Docs, but this is not used anymore, and is auto-set for each request and is not the Session token.
SO, “where is the session token then?” you might ask.
The other items in the header that start with 1s, 2s and so on are different session variables that are passed. In this case, the session token is ’20s’ followed by the version 4 UUID auto created by the “Autocomplete Widget”. A keen eye will also notice that for the 3 screenshots below they are the same. I have a fifth screenshot after the page refreshes that shows that the Session Token has changed. You can see in my code that I did not specify those things, but because I am using the “Autocomplete Widget” they are done for me.