How to fire place_changed event for Google places auto-complete on Enter key

60,276

Solution 1

Adapted from Jonathan Caulfield's answer:

$('.search-location').keypress(function(e) {
  if (e.which == 13) {
    google.maps.event.trigger(autocomplete, 'place_changed');
    return false;
  }
});

Solution 2

I've encountered this problem as well, and came up with a good solution. In my website I wanted to save the autocomplete.getPlace().formatted_address in a hidden input prior to submission. This worked as expected when clicking the form's submit button, but not when pressing the Enter key on the selection in the autocomplete's dropdown menu. My solution was as follows:

$(document).ready(function() {

    // Empty the value on page load
    $("#formattedAddress").val("");
    // variable to indicate whether or not enter has been pressed on the input
    var enterPressedInForm = false;

    var input = document.getElementById("inputName");
    var options = {
      componentRestrictions: {country: 'uk'}
    };
    autocomplete = new google.maps.places.Autocomplete(input, options);

    $("#formName").submit(function(e) {
        // Only submit the form if information has been stored in our hidden input
        return $("#formattedAddress").val().length > 0;
    });

    $("#inputName").bind("keypress", function(e) {
        if(e.keyCode == 13) {
            // Note that simply triggering the 'place_changed' event in here would not suffice, as this would just create an object with the name as typed in the input field, and no other information, as that has still not been retrieved at this point.

            // We change this variable to indicate that enter has been pressed in our input field
            enterPressedInForm = true;
        }
    });

    // This event seems to fire twice when pressing enter on a search result. The first time getPlace() is undefined, and the next time it has the data. This is why the following logic has been added.
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        // If getPlace() is not undefined (so if it exists), store the formatted_address (or whatever data is relevant to you) in the hidden input.
        if(autocomplete.getPlace() !== undefined) {
            $("#formattedAddress").val(autocomplete.getPlace().formatted_address);
        }
        // If enter has been pressed, submit the form.
        if(enterPressedInForm) {
            $("#formName").submit();
        }
    });
});

This solution seems to work well.

Solution 3

Both of the above responses are good answers for the general question of firing a question when the user presses "enter." However - I ran into a more specific problem when using Google Places Autocomplete, which might have been part of the OP's problem. For the place_changed event to do anything useful, the user needs to have selected one of the autocomplete options. If you just trigger 'place_changed', the if () block is skipped and the cookie isn't set.

There's a very good answer to the second part of the question here: https://stackoverflow.com/a/11703018/1314762

NOTE: amirnissim's answer, not the chosen answer, is the one to use for reasons you'll run into if you have more than one autocomplete input on the same page.

Share:
60,276
Admin
Author by

Admin

Updated on December 30, 2020

Comments

  • Admin
    Admin over 3 years

    The click seems to fire the event and set the cookies but pressing enter to submit doesn't set the cookies and instead the page redirects without the cookies.

    function locationAuto() {
            $('.search-location').focus(function () {
            autocomplete = new google.maps.places.Autocomplete(this);
            searchbox = this;
    
            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                var thisplace = autocomplete.getPlace();
                if (thisplace.geometry.location != null) {
                    $.cookie.raw = true;
                    $.cookie('location', searchbox.value, { expires: 1 });
                    $.cookie('geo', thisplace.geometry.location, { expires: 1 });
                }
            });
    });
    

    The .search-location is a class on multiple textboxes. There is a submit button that takes the values from the cookies and redirects (server side)