A working answer for 2020.
I've combined the best answers on this page and written it in straightforward ES6. No jQuery, 2nd API request, or IIFE needed.
Basically, we simulate a ↓ (down-arrow
) keypress whenever the user hits return inside the autocomplete field.
First, assuming in your HTML you have something like <input id="address-field">
, set up the identification of your address field like this:
const field = document.getElementById('address-field')
const autoComplete = new google.maps.places.Autocomplete(field)
autoComplete.setTypes(['address'])
Then add this on the next line:
enableEnterKey(field)
And then elsewhere in your script, to keep this functionality separate in your code if you'd like to, add the function:
function enableEnterKey(input) {
/* Store original event listener */
const _addEventListener = input.addEventListener
const addEventListenerWrapper = (type, listener) => {
if (type === 'keydown') {
/* Store existing listener function */
const _listener = listener
listener = (event) => {
/* Simulate a 'down arrow' keypress if no address has been selected */
const suggestionSelected = document.getElementsByClassName('pac-item-selected').length
if (event.key === 'Enter' && !suggestionSelected) {
const e = new KeyboardEvent('keydown', {
key: 'ArrowDown',
code: 'ArrowDown',
keyCode: 40,
})
_listener.apply(input, [e])
}
_listener.apply(input, [event])
}
}
_addEventListener.apply(input, [type, listener])
}
input.addEventListener = addEventListenerWrapper
}
You should be good to go. Essentially, the function captures each keypress in the input
field and if it's an enter
, simulates instead a down-arrow
keypress. It also stores and rebinds listeners and events to maintain all functionality of your Google Maps Autocomplete()
.
With thanks to earlier answers for much of this code, particular amirnissim and Alexander Schwarzman.