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.
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.
The following code defines the HTML elements to hold the Google Map, search input field, and geo-location data.
searchInput
) where the autocomplete addresses search will be added.map
) to display the Google Map.<!-- 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>
The Google Maps JavaScript API with Places Library helps to search the places and display location predictions in an autocomplete box.
libraries=places
).<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.
The initMap() function attach autocomplete feature to the specified search input field using Google Maps Places library.
searchInput
) with Autocomplete() method of the Places library.autocomplete.getPlace()
).
formatted_address
– Full addressgeometry.location.lat()
– Latitudegeometry.location.lng()
– Longitudeaddress_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
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
Im getting this error.
Autocomplete’s returned place contains no geometry
With this Autocomplete search box i want to add geolocation button also how can i do?
I think you have to first create biling account, then Key will work
Thank you very much for this. Saved me a lot of time! God bless!
a whole day i’m finding this step, and you are the hero bro.. thank’s
How can one add JSON or xml support for markers ?
Thanks much!
how to make click and get location and address info?
Question me, what if the pin can be sliding on Maps.?
so it can be done also with click & drag
thaks a lot 🙂
Thank you! Epic tutorial
add function for when new place search then near by place display.
Please add function: drag & drop postion location on map. Thank you so much!