Using the Google Maps JavaScript API (via <script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places&callback=initAutocomplete" async defer></script>
), my address input ...
... shows autocomplete info when I type "1251" ...
... and adds the complete address to the input when I click the address (or hit enter):
Currently, if I click the address input again (after the address has been added), it simply adds focus to the input and nothing else:
My question is: When clicking an already autocompleted input, how do I trigger the dropdown again, using the input's data?
Hitting delete once (simply changing the ending from USA
to US
) re-opens the dropdown, but I don't want the user to have to change the entry to see the pulldown. Here's what I've tried:
$('.geoloc input').on({
// neither 'place_changed' nor 'focus' trigger the dropdown (doesn't work)
click: function(){
google.maps.event.trigger(this, 'place_changed');
// or
google.maps.event.trigger(this, 'focus', {});
},
// enter selects first address from dropdown (works)
keydown: function(e){
if (e.keyCode == 13) {
google.maps.event.trigger(this, 'keydown', {keyCode:40});
google.maps.event.trigger(this, 'keydown', {keyCode:13});
this.blur();
}
}
});
What's the correct method for programmatically triggering the dropdown using the field value?
I think I know what you're trying to accomplish. You want the state of the text field to be preserved so that when focus is regained, it can revert back to where you were. Would something like this work for you?
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
input.addEventListener('input', function () {
this.dataset.originalVal = this.value;
});
input.addEventListener('focus', function () {
this.value = input.dataset.originalVal ? input.dataset.originalVal : this.value;
});
input {
width: 300px;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="searchTextField" type="text">