If you ever used Google Places API, you’re probably familiar with types option, which allows you to restrict autocomplete results in different ways. I had a requirement to show only cities in UK. So, first of all I tried (cities) type in conjunction with componentRestrictions:
Good enough, but my goal was to show and prefill input with cities only. For now, after picking a city it’ll put “City, Country” in box. The solution is quite simple, you just need to specify the country in the Google API call with a help of ®ion= parameter:
During the search for this solution I’ve collected other tips for Google places autocomplete. I’m going to post them below, hope they will be useful.
To get rid of the pins on the left side of the list add following css:
To handle list items returned by the Google API
document.addEventListener('DOMNodeInserted',(event) ->target = $(event.target)iftarget.hasClass('pac-item')# replacing "Some City United Kingdom" to "Some City" for each list element# warning: on click it will still autofill input with "Some City, United Kingdom"target.html(target.html().replace(/UnitedKingdom<\/span>$/,"</span>")))
To handle place selection you should add an event listener. It’s helpful if you want, for example, to perform AJAX call, since regular onChange won’t work.
google.maps.event.addListener(autocomplete,'place_changed',-># Here you can use:# $('.your-input').val() to get the value from your input# autocomplete.getPlace() to get detailed information about place chosen# Below is the hack to replace input content from "City, Country" to "City"# when using 'types': ('cities') without specific region.# And although I don't recommend to use it, since it flashes while# changing an input content; maybe someone will need it for other purposeplace = autocomplete.getPlace()ifplace.address_componentscity = place.address_components&&place.address_components.short_name||''input.blur()setTimeout(->input.val(city)10))