Search Location with Google Maps JavaScript API Place Autocomplete

Google Maps JavaScript API provides the feature to create location search with autocomplete. The user input will be bound and used to get the location suggestions by autocomplete service. When the user types something on this input field, the Google API will return the related addresses. These addresses are suggested to the user using Google Maps JavaScript API Place Autocomplete widget.

Google Maps Places web service is used to implement map-based location search with autocomplete. So, we have to enable Google Maps Places library by selecting a project in the Google API Console. We have seen more examples based on Google Maps JavaScript API. For example, getting current location, plotting dynamic locations on map and many. So, I am assuming that you know how to create and select a project to get API key and enable required library in Google API Console.

HTML Layer to Deploy Map and Place Autocomplete Widget

In this HTML code, I have created layers to deploy map and the Place Autocomplete widget. I have added a search input field and bind this field input with the Place Autocomplete library call to get the related addresses in a suggestion box. The suggestion box content will be put into a target div element below the search input. When the user selects a location from the suggestion box, then the location will be marked on the map with the information window. I have supplied the content of the information window based on the selected location.

Initialize Map and Invoke Place Autocomplete

In this JavaScript I have created a function initMap() to set the Google Maps JavaScript API defaults. After setting the default options I deploy the map layer in the viewport. This initialization will be invoked by importing the Google API JavaScript by sending the API key. Added to the API key, we have to specify library parameter to load the Google Maps Place library.

On typing addresses in the search input box, place autocomplete suggestion box will be responded. By changing the location from the place autocomplete suggestion box, the listener function will add the marker to the map for the selected location. Also, I data to the information window popped up near the location marger