Everyone nowadays uses Google for everything from finding the weather to maps and directions. Many businesses too add locations on their website. And you might have seen the photos that you take at a particular place automatically detecting the location. 

In this blog, I will show you how to implement Google Places Autocomplete functionality so as to fill location(address) using the Google API key.

What is Google Places Autocomplete?

The Place Autocomplete service is a web service that responds to HTTP requests with location predictions. A textual search string and optional geographic bounds are specified in the request. 

The service can be used to provide autocomplete capabilities for text-based geographic searches, returning places like businesses, addresses, and points of interest as the user inputs.

Many projects require filling in the full address or location fields. If you create a custom address autocomplete, that takes a lot of time. Google simply provides a google places API key that helps to easily autocomplete search address or location. 

You can search for locations using either proximity or a text string. A Place Search produces a list of places and summary information for each one; a Place Details query provides further information.

A Find Place request accepts text input and returns a location. The input can be any type of Places text data such as a name, address, or phone number. 

The request, however, must be a string. A Find Place request that contains non-string data, such as a LAT/LNG coordinate or plus code, results in an error.

google places autocomplete implementation a step by step guide

In the above screenshot, you can see that with the help of Google Map Place API, you can easily find any place just by pressing the first letter of the place or area. 

Using Google API

The first step is to create a Google API key. So to create an API key, just follow the steps given below. 

Visit the Google Developer console for your API key. Now you can follow the steps given below:

create a google api key

Step 1: Select the Dashboard that you can see on the left side of the screen. 

Step 2: Click on Select Project. 

Step 3: Click on Create New Project.

Once you click on ‘create a new project,' the below-mentioned window will open on your screen, and you can create a new project.

create a new project

After successfully creating a project, the next thing is to select the side menu bar and click credentials. Here, you can create your Google API key. 

credentials to get your google api

 Click on the API key, and the below-mentioned window will open.

create credentials

Now you can set HTTP Referrers like http://localhost/YOUR_FILE_PATH. You can do this by opening your localhost path and adding it.

add your local host path

Now that you are done with the Google Map API setup, it is better to make sure your Google Map Place API key is enabled.  

You can check if your API key is enabled or not by :

Step 1: Choose the ‘Library' option.

choose library

Step 2: To check if the API is enabled, select Places API.

select places api

The window will open, indicating whether or not the API is enabled. 

enable api key

Now you need to create one HTML form name AutoAddress.html and put the HTML code in this file:

<!DOCTYPE html>

<html>

<head>

  <meta charset=”UTF-8″>

  <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

  <meta http-equiv=”X-UA-Compatible” content=”ie=edge”>

  <link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css” />

  <script src=”//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js”></script>

  <title>Google map Places Autocomplete – Tutsmake.com</title>

 <style>

    .container{

    padding: 10%;

    text-align: center;

   } 

 </style>

</head>

<body>

<div class=”container”>

    <div class=”row”>

        <div class=”col-12″><h2>Google Places Autocomplete InputBox Example Without Showing Map</h2></div>

        <div class=”col-12″>

            <div id=”custom-search-input”>

                <div class=”input-group”>

                    <input id=”autocomplete_search” name=”autocomplete_search” type=”text” class=”form-control” placeholder=”Search” />

                    <input type=”hidden” name=”lat”>

                    <input type=”hidden” name=”long”>

                </div>

            </div>

        </div>

    </div>

</div>

</body>

</html>

put api key in the script

Finally, you now have your Google API key that is enabled. You need to put the API key in the script where it is written ‘PUT_YOUR_API_KEY_HERE.'

<script type=”text/javascript” src=”https://maps.googleapis.com/maps/api/js?key=PUT_YOUR_API_KEY_HERE&libraries=places“></script>

<script>

  google.maps.event.addDomListener(window, ‘load', initialize);

    function initialize() {

      var input = document.getElementById(‘autocomplete_search');

      var autocomplete = new google.maps.places.Autocomplete(input);

      autocomplete.addListener(‘place_changed', function () {

      var place = autocomplete.getPlace();

      // place variable will have all the information you are looking for.

      $(‘#lat').val(place.geometry[‘location'].lat());

      $(‘#long').val(place.geometry[‘location'].lng());

    });

  }

</script>

set up the code google places

You can now run the file on your local system as you have set up the code. You will see the output as shown in the image below. 

final output

You can search any place by clicking the first letter of the place. For example, if you are looking for Canada, once you press ‘C,' it will show all the palaces starting with the letter' C.'

Useful Points to Note

Here are a few points that you should keep in mind during API use:

  • Please make sure to check your API key so as to ensure it is enabled. It should be enabled because if your API key is disabled, you will not be able to use it.
  • Google Map Key is a paid version. Google will give it to you for free on some requests. But once you cross your request limit, it will start charging you a fee to use the same. So please take care to check in to your request limits while using Google Map API.
  • While creating your Google Map API key, Google will ask you to add your debit or credit card. Without adding your card information, you will not be able to proceed with Google Map API key use. 

Wrapping Up

I hope this blog helped you understand how to implement Google Places autocomplete using the Google API key. 

You can use autocomplete to emulate the type-ahead search functionality of the Google Maps search box in your applications. When a user begins typing an address, autocomplete fills in the blanks.

APIs are useful in many ways, like you can get Time Doctor logged data using API, and even create custom objects on HubSpot using API. 

Are you still stuck and need help? Our experts can help you out. Feel free to contact us

Frequently Asked Questions

Query Autocomplete and Place Autocomplete are distinct features offered by the Google Places API, each serving a unique purpose in location-based applications. Query Autocomplete provides real-time suggestions based on user input, offering completion to search terms or phrases. It assists users in refining their search queries by suggesting relevant keywords, making it valuable for search engines and content discovery. On the other hand, Place Autocomplete delivers location-specific suggestions, aiding users in entering precise addresses or points of interest.

The Google Places API is a set of application programming interfaces (APIs) provided by Google that allows developers to integrate location-based information and services into their web and mobile applications. It enables developers to access a wide range of place-related data and functionalities, making it easier to create location-aware applications and services.

Google Autocomplete offers several benefits, enhancing user experiences across web and mobile applications. Firstly, it speeds up the search process by providing real-time suggestions as users type, improving search efficiency. Secondly, it reduces errors and typos by offering accurate search queries or location input. Thirdly, it assists in content discovery by suggesting relevant keywords or places, enhancing navigation and user engagement.

Google Places operates as a location-based service which combines a vast database of location-related data, including business listings, user-generated content, and geographical information. When a user initiates a search query on Google Maps or other Google platforms, the query is sent to Google Places. Google's sophisticated algorithms analyze the query, incorporating factors like the user's location and context. Based on this analysis, Google Places generates a list of relevant place recommendations, which are ranked and displayed to the user.