How to programmatically input a search string and trigger places_changed for Google Maps API?

Viewed 4029

So I have a search page with a location input. If a user comes from another page with a search query, I want to programmatically input this query into the input and trigger a place changed.

Here's what I have so far:

var searchBox = new google.maps.places.SearchBox(input);

$('input#location').val(searchQuery);
google.maps.event.trigger(searchBox, 'places_changed');

However, this gives me the error Cannot read property 'length' of undefined for this line of my places_changed function:

var places = searchBox.getPlaces();

if (places.length == 0) {
  return;
}

So clearly searchBox returns undefined for getPlaces() when the input has been filled programmatically. How can I get around this?

UPDATE: Here is a JSFiddle to exemplify what I mean.

1 Answers
Related