17

I understand that in order to fire the place_changed event programmatically with the google maps javascript API v3 you do the following:

google.maps.event.trigger(autocomplete, 'place_changed');

However this simply fires the callback specified in the event and does not actually do anything to the <input> element that is attached.

What I need to do is programmatically change the selection in the autocomplete <input> to a specific location or place specified within the place object retrieved earlier via:

autocomplete.getPlace()

I can of course directly change the value in the input:

input.value = 'Whatever';

But doing this does not change the autocompletes selection. After doing so the user has to delete the whole string in the <input>, and then finally begin typing again, in order to get the autocomplete predictions to show up again.

So to summarise I would like to change the selection of a google maps autocomplete input programmatically, using a place object obtained from the places/autocomplete api. Is there any way to do this?

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
Gordo
  • 779
  • 9
  • 21
  • Presumably you need to trigger a keyboard event (keydown, keyup or keypress) on the input element after its value has been programmatically changed. This is easy with jQuery but can also be done in raw javascript - https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Events/Creating_and_triggering_events. – Beetroot-Beetroot Jul 25 '13 at 22:35

1 Answers1

12

If you have the place object you can do it via

autocomplete.set("place", place)

That will trigger the place_changed event in the autocomplete

jeffsaracco
  • 1,259
  • 12
  • 21
  • 1
    will be great if you can provide the documentation to `set()` command – GusDeCooL May 18 '17 at 06:26
  • 3
    Here is the documentation for `set` - though it's entirely unhelpful - https://developers.google.com/maps/documentation/javascript/reference#MVCObject (Autocomplete extends `MVCObject` https://developers.google.com/maps/documentation/javascript/reference#Autocomplete) – jeffsaracco Jul 05 '17 at 18:20
  • Related: if you have an address but don't have the `place` object, see https://stackoverflow.com/questions/9892092/need-to-manually-start-the-google-places-autocomplete?noredirect=1&lq=1 – Alex R Oct 11 '20 at 22:33
  • I don't know how I can get things done without SO. Thanks! – Billy Mar 29 '21 at 19:59