Using Google Maps JavaScript API and Places library, you can easily add an autocomplete places search box to a web page. We’ll use HTML and JavaScript to implement places search box with autocomplete address suggestion.
We're going to be building a basic run-of-the-mill address form you've likely seen on thousands of sites. However, we're going to use the Google Maps and Places JavaScript APIs to autofill the form when the user types in either the street address
CSS Code:
.wrapper{
text-align: center;
width: 800px;
margin: auto;
}
input{
height: 30px;
width: 355px;
padding-left:10px
}
HTML Code:
<div class="wrapper">
<label>Address</label>
<input id="autocomplete" placeholder="Enter your address"
onFocus="geolocate()" type="text"/>
</div>
JavaScript Code:
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
{types: ['geocode']});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
}
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
You can specify a Google API key using key=Your_Google_API_Key parameter when loading the Google Maps JavaScript API.
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-GOOGLE-API-KEY&libraries=places&callback=initAutocomplete" async defer></script>