How to add Google Maps Autocomplete to a search box

How to add Google Maps Autocomplete to a search box

Most of the time when creating a registration form, you will ask the user to type in the city they live in.
And you want to make the user’s life easier by auto completing the city name as they type.
Ever wondered how to add Google Maps autocomplete for a textbox?

Google Maps AutoComplete API

Using a free service from google, you can easily add the autocomplete to any textbox.

The sample below demonstrates how it’s done and the highlighted rows are the important parts.

Enjoy

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<label for="locationTextField">Location</label>
<input id="locationTextField" size="50" type="text" />
<script>
	function init() {
		var input = document.getElementById('locationTextField');
		var autocomplete = new google.maps.places.Autocomplete(input);
	}
google.maps.event.addDomListener(window, 'load', init);
</script>

https://gist.github.com/jon-kim/0f3ab7d88699077382dd28b70ea88326

13 thoughts on “How to add Google Maps Autocomplete to a search box

    1. Thanks for your comments.
      It’s not hard to get the longitude and latitude.
      All you have to do is add the following code on line 9.

      [HTML]
      <div id="output" />
      [/HTML]

      And add the following code after line 13.

      [JS]
      google.maps.event.addListener(autocomplete, ‘place_changed’,
      function() {
      var place = autocomplete.getPlace();
      var lat = place.geometry.location.lat();
      var lng = place.geometry.location.lng();
      document.getElementById("output").innerHTML = "Lat: "+lat+"<br />Lng: "+lng;
      }
      );
      [/JS]

      https://gist.github.com/jon-kim/3c4f71db4e65538d5896c0267bc225a2#file-autocompletelnglatgooglemapapi-html

    1. Doesnt work for me too!! the search box yields no result after typing in it!! has something changed with the google API?

  1. Kim,
    thank you for that above.
    But I cannot integrate it on my site.
    Wasn’t the respective API cancelled by google?

    So, I need your help for this and, of course, I would pay for this.
    Pls help me.

  2. Code doesn’t work on my aspx page.. some error is occurring while typing on textbox

  3. Hey man! It works fine but when i put street map on my code then it stops working! Maps work only without this and this works only without maps! any solution to work both? So when someone search something in the search box i want to show him that ! What i am saying is that i want and the maps in my website!

  4. I’m unable to do it on localhost even though i literally copied your code and pasted it.
    I tried adding my API still no result instead the search box stops taking input with an exclamation sign

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.