Javascript – How to add Google Maps Autocomplete search box

autocompletegoogle-maps-api-3javascript

I am trying to add a Google autocomplete search box to a website so that users can search for an address as easily as possible.

My problem is, I have looked a numerous questions on here as well as the Google Maps Javascript API v3 regarding this and some tutorials yet they all bundle together the autocomplete functionality with mapping it on an embedded Google map.

I don't need to map the location visually, I just need the autocomplete box for now, unfortunately I cannot work out which parts of the API are relevant to this and every example I have looked at includes plenty of JS for mapping.

How can I ONLY add the autocomplete input functionality?

Best Answer

A significant portion of this code can be eliminated.

HTML excerpt:

<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>

Javascript:

function initialize() {
  var input = document.getElementById('searchTextField');
  new google.maps.places.Autocomplete(input);
}

google.maps.event.addDomListener(window, 'load', initialize);