Search Location with Google Maps JavaScript API Place Autocomplete

Last modified on May 3rd, 2018 by Vincy.

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.

map-location-search

View Demo

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.

<div class="pac-card" id="pac-card">
    <div>
        <div id="label">Location search</div>
    </div>
    <div id="pac-container">
        <input id="pac-input" type="text" placeholder="Enter a location">
        <div id="location-error"></div>
    </div>
</div>
<div id="map"></div>
<div id="infowindow-content">
    <img src="" width="16" height="16" id="place-icon"> <span
        id="place-name" class="title"></span><br> <span
        id="place-address"></span>
</div>

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

<script>
	function initMap() {
		var centerCoordinates = new google.maps.LatLng(37.6, -95.665);
		var map = new google.maps.Map(document.getElementById('map'), {
			center : centerCoordinates,
			zoom : 4
		});
		var card = document.getElementById('pac-card');
		var input = document.getElementById('pac-input');
		var infowindowContent = document.getElementById('infowindow-content');

		map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);

		var autocomplete = new google.maps.places.Autocomplete(input);
		var infowindow = new google.maps.InfoWindow();
		infowindow.setContent(infowindowContent);

		var marker = new google.maps.Marker({
			map : map
		});

		autocomplete.addListener('place_changed',function() {
			document.getElementById("location-error").style.display = 'none';
			infowindow.close();
			marker.setVisible(false);
			var place = autocomplete.getPlace();
			if (!place.geometry) {
				document.getElementById("location-error").style.display = 'inline-block';
				document.getElementById("location-error").innerHTML = "Cannot Locate '" + input.value + "' on map";
				return;
			}

			map.fitBounds(place.geometry.viewport);
			marker.setPosition(place.geometry.location);
			marker.setVisible(true);

			infowindowContent.children['place-icon'].src = place.icon;
			infowindowContent.children['place-name'].textContent = place.name;
			infowindowContent.children['place-address'].textContent = input.value;
			infowindow.open(map, marker);
		});
	}
</script>
<script
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCXMpUMMrjVgbWeWF99SfuFQhe06-ST62s&libraries=places&callback=initMap"
    async defer></script>

Location Search with Google Maps Place Autocomplete – Output

This screenshot shows the location marker added to the map layer based on the user input. The information window popped up near the marked location with the location details.

location-search-with-place-autocomplete-output

View DemoDownload

This PHP code tutorial was published on May 2, 2018.

↑ Back to Top

Share this Article