In this blog, we will learn how we can implement Google Places API from scratch to create an address autocomplete with JavaScript and HTML.
What is Google Places API?
Google Places API can be used to find locations on the basis of user's input. You can find establishments, geographical locations and specific location of interest by using Google Places API. The Places Autocomplete service returns place predictions in response when user enters name of place.
Let's Start Implementing Google Places API
- Login to the Google Cloud Platform.
- Select a project or you can create a new project.
- After successfully creating a project you'll get navigated to the dashboard, where you can see the option "ENABLE APIS AND SERVICES" in the dashboard. Click on it and you'll get navigated to the "API Library".
- In the "API Library" Search for Places API and Enable it.
- Search for Maps JavaScript API and also enable it.
- Go back to Dashboard and now you will see your enabled APIS.
Now we need to get API key. The API key is a unique identifier that is there to authenticate requests which are associated with your project. Steps to get API key:
- Navigate to the "Credentials" Section, you'll find it inside the dashboard.
- Now Click on "CREATE CREDENTIALS" and select "API Key". A new API Key will get generated just copy it we will use it later.
We are done with the Google Cloud Platform now let's move to the javascript section where we will use API Key.
- First create a HTML file and add basic HTML structure with an input box, type "text" and give it an "id" of anything you want, in my case i'm using "search_input" as an "id" of input box.
- Add jQuery CDN in the head.
- Now let's add API Key in the head of HTML within Script tag. Script tag will look like this it'll contain the API and Key. Add your API Key in place of "EnterYourKey".
<script defer src="https://maps.googleapis.com/maps/api/js?key=EnterYourKey&libraries=places"></script>
- Create a Script tag for our JavaScript code.
- Now we'll use jquery's to trigger the Google Places API function after document gets ready.
- Now we have to Get the Input text element using "document.getElementById('IDofInputBox') and pass it inside the Google Places API Autocomplete function.
- The Autocomplete function now can access the Text Input Element.
- Below is the code...
<script>
$(document).ready(function () {
var autocomplete;
autocomplete = new google.maps.places.Autocomplete(
document.getElementById("search_input")
);
});
</script>
- Now open the HTML page in your browser and type something in your search input you'll see that you're getting recommendation on the basis of what you entered.
- You'll see something like this in your browser after entering something in the input box.
Thanks,
Yash Chouriya