How to create autocomplete places search box using Google Maps in JavaScript
In this article, we will show you how to create autocomplete places search box using Google Maps in JavaScript. We have already explained how to implement Google Place Autocomplete in ReactJS.
Checkout more articles on JavaScript
Steps to create autocomplete place search box
- Get Google Maps Place API key
- Use Google Maps JavaScript place API
- Add autocomplete place search box
- Output
1. Get Google Maps place API key
In the very first step, we need to get the Google Maps place API key to load the Google Maps script for autocomplete address search box. Check the following link for more information.
https://developers.google.com/maps/documentation/javascript/get-api-key
Note: Don’t forget to restrict the API key as we are using this key at the frontend side so that it will be publicly available.
2. Use Google Maps JavaScript place API
Here we will use the below API to implement the place autocomplete in JavaScript where we use the place libraries.
1 2 | https://maps.googleapis.com/maps/api/js?key=<your_google_map_api_key>&libraries=places&callback=initMap </your_google_map_api_key> |
Replace your Google Maps API key with
in the above script.
3. Add autocomplete place search box
Add the above script and initialize google maps by passing the reference of the input
search field. You will find more geometric information when you select the address from the autocomplete place search box.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <title>Autocomplete Place Search Box using Google Maps Javascript API - Clue Mediator</title> <h1>Autocomplete Place Search Box using Google Maps Javascript API - Clue Mediator</h1> <input id="placeInput" type="text" placeholder="Enter a location"> <ul> <li>Address: <span id="address-info"></span></li> <li>Latitude: <span id="lat-info"></span></li> <li>Longitude: <span id="lng-info"></span></li> </ul> <script> function initMap() { const input = document.getElementById('placeInput'); const autocomplete = new google.maps.places.Autocomplete(input); autocomplete.addListener('place_changed', function () { const place = autocomplete.getPlace(); document.getElementById('address-info').innerHTML = place.formatted_address; document.getElementById('lat-info').innerHTML = place.geometry.location.lat(); document.getElementById('lng-info').innerHTML = place.geometry.location.lng(); }); } </script> <script async="" defer="" src="https://maps.googleapis.com/maps/api/js?key=<YOUR_GOOGLE_MAP_API_KEY>&libraries=places&callback=initMap"></script> |
4. Output
Simply run the above HTML file and check the output in the browser.
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂