embed-places-icon

Google Places API Javascript Library – Create autocomplete input and work with returned data via JavaScript

Google Places API

Google offering a lot of APIs and what is best, for common use they are free! In this post, I will describe you Autocomplete functionality and something about that, what you can do with place, which can be returned by autocomplete.

Restrictions

Using of this feature is limited by count of requests per day. If you reach this number, you have to get Premium Account. For more information see this page. Now is free 150,000 request per day and that is enough 🙂
One important note. Nobody love reading Policies and Terms, but on Google developers portal is important information:

Place IDs are exempt from the caching restrictions stated in Section 10.5.d of the Google Maps APIs Terms of Service. You can therefore store place ID values indefinitely.

How to get API Key and start developing?

  1. Create (or sign in with Google account) Google Developer account here.
  2. Get your API Key in Google API Manager.
    1. Create New project.
    2. Click on your project and go to project details. In Overview panel, search Google Maps JavaScript API and Enable it.
    3. Go to Credentials project settings and from menu select Create credentials and API Key.
      1. Here you can configure a domain restrictions. This is important for secure you API Key and only calls from this domain will be enabled.
    4. Copy you API Key
  3. Use your API_KEY for using JS library.
Lets start with coding!
Here is our simple HTML code:
<!DOCTYPE html>
<html>
<head>
 <title>Location information</title>
 <meta charset="utf-8">
 <style>
        body {
            text-align:center;
            margin: 5 auto;
        }
    </style>
</head>
<body>
<input id="autocomplete" onFocus="locate()" type="text"
       placeholder="Enter a location" />
<H3> Location information:</h3>
<div id="place_info"></div>
</body>
</html>

Page contains only two important elements. First is text input element, which will be used for autocomplete and second is div element where we will print our result.

Input element have onFocus event, where we will call locate() function. This function is called when user focus to element and it will try to use browser location feature for get current location. This function will be described below.

Now we will write init function for Autocomplete and define our variables.

// Div element for printing our results
var output = document.getElementById('place_info');
// Input element for Autocomplete
var autocomplete;
// Init function to define new Autocomplete object for our input defined by ID autocomplete
// and listener for place_changed event (select place from options) to call getDetails function
functioninitAutocomplete(){
autocomplete=newgoogle.maps.places.Autocomplete((document.getElementById('autocomplete')),{types:['geocode']});
autocomplete.addListener('place_changed',getDetails);}

 

Next step is definition a locate() function, which will be called by onFocus event on input element:
function locate() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var geolocation = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
            var circle = new google.maps.Circle({
              center: geolocation,
              radius: position.coords.accuracy
            });
            autocomplete.setBounds(circle.getBounds());
          });
     }
 }

In this point we have function for inserting address by browser – locate(), if user will allow it, and we have defined Autocomplete element for our input element.

Now we have to configure which library it should be used, and set up call back for our init function –initAutocomplete(). We can do it by calling this script from source parameter:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete"
        async defer></script>

Let’s take a look on this URL. First parameter is your API Key, second is which libraries we want to receive with this API Key (we asking for places library) and third for define callback function where we want call our initAutocomplete function to initialize Autocomplete for our input element.

And here is our last function to get place details and print them! We added a listener for autocomplete for place_changed event to call getDetails function.

function getDetails() {
// Get PlaceResult object from Autocomplete
            var place = autocomplete.getPlace();
// Variable for saving our result witch default place name + ID
            var outputString = '<H4>Details for place '+ place.name + ' with ID : ' + place.place_id + '.</H4>';
// Iterate address_components array
            for (var i = 0; i < place.address_components.length; i++) {
// Add each row to our result in format: TYPE : VALUE
               outputString += place.address_components[i]["types"][0] + ' : ' + place.address_components[i]["long_name"] + '<br>';
            }
// Print it!
            output.innerHTML = outputString;
      }

Now put all together:

<!DOCTYPE html>
<html>
<head>
    <title>PlaceID</title>
    <meta charset="utf-8">
    <style>
        body {
            text-align:center;
            margin: 5 auto;
        }
    </style>
</head>
<body>
<input id="autocomplete" onFocus="locate()" type="text"
       placeholder="Enter a location" />
<H3>Location information</h3>
<div id="place_info"></div>

<script>

    var autocomplete;
    var output = document.getElementById('place_info');

        function initAutocomplete() {
            autocomplete = new google.maps.places.Autocomplete((document.getElementById('autocomplete')),{types: ['geocode']});
            autocomplete.addListener('place_changed', getDetails);
      }

      function getDetails() {
            var place = autocomplete.getPlace();
            var outputString = '<H4>Details for place '+ place.name + ' with ID : ' + place.place_id + '.</H4>';

            for (var i = 0; i < place.address_components.length; i++) {
               outputString += place.address_components[i]["types"][0] + ' : ' + place.address_components[i]["long_name"] + '<br>';
            }
            output.innerHTML = outputString;
      }

      function locate() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var geolocation = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
            var circle = new google.maps.Circle({
              center: geolocation,
              radius: position.coords.accuracy
            });
            autocomplete.setBounds(circle.getBounds());
          });
        }
      }

    </script>

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete"
        async defer></script>

</body>
</html>

 

Summary

This was very simple example, but I hope that it will help you. For more information about returned PlaceResult see docs. Of course, here we are only echo result, but you are able to send these data to next business logic or store place_id variable to DB for capturing and reusing.
Aleš Laňar
Senior Engineer Software ve společnosti CA Technologies

Leave a Reply

Your email address will not be published. Required fields are marked *