Home > Back-end >  Google Autocomplete API - modify and submit search
Google Autocomplete API - modify and submit search

Time:02-03

We have a textbox input hooked up to Google's Autocomplete API.

Many suburbs in Australia have duplicate names per state e.g. Balmoral NSW. There is one in particular that always returns the "wrong" result for our users if they select it from the dropdown since Google does not show postcodes or fully qualified information. We are planning to detect the entered value via the place_changed event and show two buttons they can click on to disambiguate their selection with a string that will match each location directly. This part is working.

However I can't figure out how to submit it automatically as a new search.

What does work, if I paste each line in the console, is the following:

var addressTextBox = $("input[id$='addressTextBox']");
google.maps.event.trigger(addressTextBox.get(0), 'focus', {});
addressTextBox.get(0).dispatchEvent(new KeyboardEvent('keydown', { 'key': 'Enter', 'keyCode': 13 }));

I have hooked up another event to take the enter keypress and automatically precede it with a down-arrow to select and submit the first item in the list, as answered in another question.

However if strung together in code it doesn't work. The dropdown appears but is not responsive to clicks, or the enter keypress goes through and searches before anything updates. There must be a delay between each line. I assume this is Google API latency so cannot be hard coded, but I can't see a way to do a callback or trigger the next step based on completion.

Is there a simpler way to submit the search directly?

We may be able to work around it by adjusting our page as though a search happened, but doing it via the actual mechanism would allow us to just rely on the regular update logic.

CodePudding user response:

I would recommend not using the widget and switching to the autocomplete service instead.

This will require hooking up your own input text box and dropdown, but it seems you may prefer that anyhow.

// Create a new session token.
var sessionToken = new google.maps.places.AutocompleteSessionToken();

// Pass the token to the autocomplete service.
var autocompleteService = new google.maps.places.AutocompleteService();
const predictions = await autocompleteService.getPlacePredictions({
  input: 'pizza near Syd',
  sessionToken: sessionToken
});

Alternatively, you could go from the user clicking on one your buttons to the code above. Ideally you would reuse the session token too.

  •  Tags:  
  • Related