Places AutocompleteWhat’s cooler than using Google’s Geocoder to let users navigate using text descriptions? Replacing the geocoder entirely with Autocomplete.

The “Places Autocomplete” feature is one of the goodies you get when you import the Places Library. I decided to test it out on my WordWhere application. WordWhere lets users select a geographic area, then search a word to see where in the region it appears most frequently.

The program still geocodes the user’s input, but the code is simpler yet more powerful. The old geocoder object below get replaced…

geocoder = new google.maps.Geocoder();


autocomplete = new google.maps.places.Autocomplete(input);

Let’s zoom out and look at the entire chunk of code used to initialize the map.

var input = document.getElementById('place');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map); 
google.maps.event.addListener(autocomplete, 'place_changed', function() {
  input.className = '';
  var place = autocomplete.getPlace();
  if (!place.geometry)  
    placeInput.className = 'notfound'; 
  else if (place.geometry.viewport)  

I pass the Autocomplete constructor the input text field (grabbed via its ID of “place”). From that point on the Google object basically takes over the input field. I ran into problems with another program that tried to manipulate the input field via the DOM, which resulted in mysterious behavior. But as long as the field gets input only from the user, you’re fine.

The bindTo() method will bias the autocomplete results to the region in the viewport, even if the user pans and zooms.

Once the user accepts one of the autocomplete options, I want the map to show their selection. The event listener lets me customize what happens. The results are already geocoded, so it’s just a matter of passing the location data to the map object.

That’s it, other than the optional CSS stuff thrown in. It took me about five minutes to get it running. Places Autocomplete is a cool feature that’s easy to add to your program.

For more about WordWhere, see Where Do Words Appear?

Saving Keystrokes with Places Autocomplete

Leave a Reply