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

4

35

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)

Locke answered 10/10, 2012 at 9:47 Comment(3)
This is not a Google Mapa API question.Constriction
its in the Google Maps API v3 Places LibraryLocke
The question is about firing an event on a DOM element, not about the Google Maps API.Constriction
C
45

Adapted from Jonathan Caulfield's answer:

$('.search-location').keypress(function(e) {
  if (e.which == 13) {
    google.maps.event.trigger(autocomplete, 'place_changed');
    return false;
  }
});
Constriction answered 10/10, 2012 at 10:39 Comment(2)
Nice answer. I was able to adapt this easily to do what I wanted, which was fire the autocomplete listener and THEN go ahead and submit the form.Bennion
It's been a while since this was answered so maybe something has changed in google's Autocomplete widget but if I use this code the getPlace() method on the autocomplete object will return null. The standard place_changed handler seems to get fired on keypress so just returning false from here is enough (for me) to stop the containing form from being submitted.Avirulent
E
7

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.

Eanes answered 29/12, 2015 at 23:18 Comment(2)
The comment "This event seems to fire twice when pressing enter on a search result. The first time getPlace() is undefined" saved me. All I did was check if it is not undefined inside my callback before taking action and now everything works.Pulchritude
Thanks for sharing your thoughts and solution for the bigger contextSatan
H
5

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://mcmap.net/q/264371/-google-maps-places-api-v3-autocomplete-select-first-option-on-enter

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.

Hagberry answered 2/4, 2013 at 3:47 Comment(0)
R
0

Maybe not the most user friendly solution but you could use JQuery to disable the enter key press.

Something like this...

$('.search-location').keypress(function(e) {
  if (e.which == 13) {
    return false;
  }
});
Robber answered 10/10, 2012 at 9:58 Comment(2)
I tried the code but think the auto-complete has the focus when the key is pressed rather than the textbox.Locke
Doesn't answer the question, and suggests doing something instead which is very bad UX.Avitzur

© 2022 - 2024 — McMap. All rights reserved.