Autocomplete Address Field using Google Maps JavaScript API with Places Library

Autocomplete input field allows to select a value from the pre-populated suggestions list. The autocomplete feature is very useful for the location search input field. It helps to select a proper location without typing the entire address. The autocomplete functionality can be easily added to the input field for text-based geographic location searches using Google Maps JavaScript API.

Google Maps JavaScript API with Places library provides an easy way to convert text input to a location search box using jQuery. The location autocomplete textbox can be used to get the user’s input of the address or location info. When the user starts typing in the location search field, the place predictions are listed under the input field. In this tutorial, we will show you how to add an autocomplete address field to the HTML form using Google Maps JavaScript API and jQuery.

jQuery Library

jQuery is used to trigger event handlers, so include the jQuery library first.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

Google Maps JavaScript API

Google Maps JavaScript API and Places Library, are used to search for places and display location predictions in autocomplete box.

  • Load the Google Maps JavaScript API with Places library (libraries=places).
  • Specify the API key in the key parameter.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&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.

How to Get Google Maps JavaScript API Key

Find Places with Google Maps JavaScript API

JavaScript Code:
The following JavaScript code enables autocomplete places search feature in the specified input field using Autocomplete() method of the Google Maps Places library.

  • Based on the search term, the matched places are fetched from the Places library and append to the suggestions box.
  • The latitude and longitude of the selected location are retrieved using getPlace() method.
  • Set the selected latitude & longitude,
    • to the hidden input field for getting value on form submission.
    • to the element for showing on the web page.
var searchInput = 'search_input';

$(document).ready(function () {
    var autocomplete;
    autocomplete = new google.maps.places.Autocomplete((document.getElementById(searchInput)), {
        types: ['geocode'],
    });
	
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        var near_place = autocomplete.getPlace();
        document.getElementById('loc_lat').value = near_place.geometry.location.lat();
        document.getElementById('loc_long').value = near_place.geometry.location.lng();
		
        document.getElementById('latitude_view').innerHTML = near_place.geometry.location.lat();
        document.getElementById('longitude_view').innerHTML = near_place.geometry.location.lng();
    });
});

Remove latitude & longitude on changing the input field value using jQuery.

$(document).on('change', '#'+searchInput, function () {
    document.getElementById('latitude_input').value = '';
    document.getElementById('longitude_input').value = '';
	
    document.getElementById('latitude_view').innerHTML = '';
    document.getElementById('longitude_view').innerHTML = '';
});

HTML Code:
Create an input element where the autocomplete location search will be added.

  • Define the ID attribute in the element and specify this ID as a selector (searchInput) in JavaScript code.
<!-- Autocomplete location search input --> 
<div class="form-group">
    <label>Location:</label>
    <input type="text" class="form-control" id="search_input" placeholder="Type address..." />
    <input type="hidden" id="loc_lat" />
    <input type="hidden" id="loc_long" />
</div>

<!-- Display latitude and longitude -->
<div class="latlong-view">
    <p><b>Latitude:</b> <span id="latitude_view"></span></p>
    <p><b>Longitude:</b> <span id="longitude_view"></span></p>
</div>

Country Restriction

You can add a country restriction on places search with componentRestrictions option in Autocomplete() method.

var autocomplete;
autocomplete = new google.maps.places.Autocomplete((document.getElementById(searchInput)), {
    types: ['geocode'],
    componentRestrictions: {
        country: "USA"
    }
});

Autocomplete Places Search Box using Google Maps JavaScript API

Conclusion

The location autocomplete field is very useful in the data creation form where the address information needs to be submitted. You can also use this autocomplete functionality in the location search field. Our autocomplete location search script helps you to add a user-friendly way to address input field in the web form. The autocomplete location textbox functionality can be enhanced easily as per your needs using jQuery.

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

1 Comment

  1. Ezinne Adindu Said...

Leave a reply

keyboard_double_arrow_up