Autocomplete Places Search Box using Google Maps JavaScript API

An autocomplete feature is very useful for the addresses search box. When a user starts typing an address, the autocomplete field list the suggestions based on the search term. You can use the autocomplete input field to search addresses on the web application. The autocomplete places search box can be integrated easily with the Google Maps JavaScript API.

Using Google Maps JavaScript API and Places library, you can easily add an autocomplete places search box to a web page. The Places library provides an autocomplete feature with the Maps JavaScript API. We’ll use HTML and JavaScript to implement places search box with autocomplete address suggestion. In this tutorial, we will show you how to integrate the location search box with autocomplete and display a map marked with selected location and info window using Google Maps JavaScript API.

In the example script, a search box will display with a Google map. When the user starts typing an address, an autocomplete suggestion dropdown will appear from where the user can select a location. Once a place is selected, the respective location will be pointed on a Google Map with a marker and info window. Also, the geolocation data (full address, postal code, country, latitude & longitude) will display under the Google Map.

Google Maps API Key

The API Key is required to access the Google Maps JavaScript API. Before getting started, create a project and generate an API Key on the Google API Console.

Google Map with Autocomplete Search Box

The following code defines the HTML elements to hold the Google Map, search input field, and geo-location data.

  • Create an input element (searchInput) where the autocomplete addresses search will be added.
  • Create a DIV element (map) to display the Google Map.
  • Specify the elements to display the geolocation data.
<!-- Search input -->
<input id="searchInput" class="controls" type="text" placeholder="Enter a location">

<!-- Google map -->
<div id="map"></div>

<!-- Display geolocation data -->
<ul class="geo-data">
    <li>Full Address: <span id="location"></span></li>
    <li>Postal Code: <span id="postal_code"></span></li>
    <li>Country: <span id="country"></span></li>
    <li>Latitude: <span id="lat"></span></li>
    <li>Longitude: <span id="lon"></span></li>
</ul>

Google Maps JavaScript API

The Google Maps JavaScript API with Places Library helps to search the places and display location predictions in an autocomplete box.

  • Load the Google Maps JavaScript API with Places library (libraries=places).
  • Specify an API key in the key parameter.
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=Your_API_Key"></script>

Note that: Google Maps JavaScript API and Places API must be enabled for the Google API Console Project whose API Key is used.

Autocomplete Location Search with Google Maps JavaScript API

The initMap() function attach autocomplete feature to the specified search input field using Google Maps Places library.

  • Initially, a Google Map will appear based on the specific latitude & longitude.
  • The autocomplete feature is enabled for the specific input field (searchInput) with Autocomplete() method of the Places library.
  • Once an address is selected from the autocomplete dialog,
    • The location is marked on the Google Map with an info-window.
    • The geo location data is retired from autocomplete object the using getPlace() method (autocomplete.getPlace()).
      • formatted_address – Full address
      • geometry.location.lat() – Latitude
      • geometry.location.lng() – Longitude
      • address_components – Postal code and country
<script>
function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -33.8688, lng: 151.2195},
      zoom: 13
    });
    var input = document.getElementById('searchInput');
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.bindTo('bounds', map);

    var infowindow = new google.maps.InfoWindow();
    var marker = new google.maps.Marker({
        map: map,
        anchorPoint: new google.maps.Point(0, -29)
    });

    autocomplete.addListener('place_changed', function() {
        infowindow.close();
        marker.setVisible(false);
        var place = autocomplete.getPlace();
        if (!place.geometry) {
            window.alert("Autocomplete's returned place contains no geometry");
            return;
        }
  
        // If the place has a geometry, then present it on a map.
        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17);
        }
        marker.setIcon(({
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(35, 35)
        }));
        marker.setPosition(place.geometry.location);
        marker.setVisible(true);
    
        var address = '';
        if (place.address_components) {
            address = [
              (place.address_components[0] && place.address_components[0].short_name || ''),
              (place.address_components[1] && place.address_components[1].short_name || ''),
              (place.address_components[2] && place.address_components[2].short_name || '')
            ].join(' ');
        }
    
        infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
        infowindow.open(map, marker);
      
        // Location details
        for (var i = 0; i < place.address_components.length; i++) {
            if(place.address_components[i].types[0] == 'postal_code'){
                document.getElementById('postal_code').innerHTML = place.address_components[i].long_name;
            }
            if(place.address_components[i].types[0] == 'country'){
                document.getElementById('country').innerHTML = place.address_components[i].long_name;
            }
        }
        document.getElementById('location').innerHTML = place.formatted_address;
        document.getElementById('lat').innerHTML = place.geometry.location.lat();
        document.getElementById('lon').innerHTML = place.geometry.location.lng();
    });
}
</script>

Specify the initMap() function in the callback parameter to initialize this method on the Google Maps JavaScript API load.

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

Autocomplete Address Field using Google Maps JavaScript API with Places Library

Conclusion

If you want to make the location search functionality user-friendly, the autocomplete feature is the best option. The autocomplete location search field can be used in many places where you want to allow the user to input the address. Our example code provides an easy way to add autocomplete functionality with the places search field using JavaScript.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

12 Comments

  1. Carlos Said...
  2. Dhamiwal Said...
  3. Yogesh Said...
  4. Reg Said...
  5. Perjuang Said...
  6. Barr Said...
  7. Suki Said...
  8. Mehmet Said...
  9. Eko Said...
  10. Ed Said...
  11. Gaurav Said...
  12. LE TUAN ANH Said...

Leave a reply

keyboard_double_arrow_up