Sometimes, we want to add a Google Maps Autocomplete search box with JavaScript.
In this article, we’ll look at how to add a Google Maps Autocomplete search box with JavaScript.
How to add a Google Maps Autocomplete search box with JavaScript?
To add a Google Maps Autocomplete search box with JavaScript, we can add an input.
For instance, we write
<head>
...
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
...
</head>
<body>
...
<input id="searchTextField" type="text" size="50" />
...
</body>
to add the Google Maps script and search input.
Then we write
const initialize = () => {
const input = document.getElementById("searchTextField");
new google.maps.places.Autocomplete(input);
};
google.maps.event.addDomListener(window, "load", initialize);
to select the input with getElementById
in the initialize
function.
Then we call the Autocomplete
constructor with input
to convert it to a Google Maps search input.
Then we call addDomListener
with window
, 'load'
, and initialize
to call initialize
when the DOM loads.
Conclusion
To add a Google Maps Autocomplete search box with JavaScript, we can add an input.