Events other than 'place_changed' for Google Maps Autocomplete
Solution 1:
There is only one documented event in the Google Maps Javascript API v3 for the google.maps.places.Autocomplete class, place_changed
You can add standard HTML event listeners to it (not sure if that will affect the Autocomplete functionality).
Solution 2:
This comes down to checking whether you receive a place.geometry
object, as it is shown in their official example. As simple as that!
function initialize() {
var ac = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')), {
types: ['geocode']
});
ac.addListener('place_changed', function() {
var place = ac.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
// Do anything you like with what was entered in the ac field.
console.log('You entered: ' + place.name);
return;
}
console.log('You selected: ' + place.formatted_address);
});
}
initialize();
#autocomplete {
width: 300px;
}
<input id="autocomplete" placeholder="Enter your address" type="text"></input>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
Solution 3:
If you add your own input handler (for example catching CR after user entering his own text), autocomplete and your function may call your method back to back. My solution is to use throttle to avoid the repeated call:
$('#sell_address_input').keyup(function(e){ if(e.keyCode==13){throttle(addressEntered(),1000)}});
....
function throttle(callback, limit) {
var wait = false; // Initially, we're not waiting
return function () { // We return a throttled function
if (!wait)
{ // If we're not waiting
callback.call(); // Execute users function
wait = true; // Prevent future invocations
setTimeout(function ()
{ // After a period of time
wait = false; // And allow future invocations
}, limit);
}
}
}