Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger google maps autocomplete on focus out [duplicate]

How to reproduce the issue:

on this page https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform

choose some address, for example 20 Water Street, New York City, NY, United States, (as expected the fields are being filled with the info). Now, e.g. in address change 20 to 10, and instead of choosing the address from the suggested list, just click somewhere on the page. The suggested list disappears, the new address 10 Water Street, New York City, NY, United States remains in the input field, but the fields information is not being updated.

I am using this to get the latitude and longitude. So, if the user instead of clicking on the address, clicks outside, it will look like, that he changed the address, but in fact I still will have the previous address's Lat and Lng.

here is the init function

var autocomplete;
function initialize() {
    autocomplete = new google.maps.places.Autocomplete(
    /** @type {HTMLInputElement} */
    (document.getElementById('addressAutocomplete')), {
        types : [ 'geocode' ]
    });

    google.maps.event.addListener(autocomplete, 'place_changed', function() {
        var place = autocomplete.getPlace();
        console.log(place);
    });
}

I was thinking smth like this can work, but it does not, this line console.log(place); outputs undefined

$(document).ready(function() {
    $(document).on('focusout', '#addressAutocomplete', function() {
        google.maps.event.trigger(autocomplete, 'place_changed', {});
    });
});

Thanks

like image 905
dav Avatar asked May 12 '14 05:05

dav


1 Answers

I had a similar issue (that anything in the given field should be valid Google Maps address), and based on Alexandre Boulier's suggested link built a solution inspired from this one, that may help you. The idea is :

  • when the user does something else than click on a Google Maps suggestion
  • trigger the event to move focus on the first suggestion
  • trigger the event to select it

I copy the result for my own code (with Jquery) :

//// Ensuring that only Google Maps adresses are inputted
function selectFirstAddress (input) {
    google.maps.event.trigger(input, 'keydown', {keyCode:40});
    google.maps.event.trigger(input, 'keydown', {keyCode:13});
}

// Select first address on focusout
$('#content').on('focusout', 'input#xxx__zzz', function() {
    selectFirstAddress(this);
});

// Select first address on enter in input
$('#content').on('keydown', 'input#xxx__zzz', function(e) {
    if (e.keyCode == 13) {
        selectFirstAddress(this);
    }
});

For me it works, I hope it helps !

like image 186
PolRaguénès Avatar answered Sep 18 '22 17:09

PolRaguénès