Trigger Google Places Autocomplete

2019-02-06 10:01发布

I am trying to attach a virtual keyboard to bind to a Google places autocomplete input.

If I physically type in a letter in the input, a Google-powered dropdown displays the autocomplete predictions based on where the map is centered. If I click on a virtual keyboard key, the input gets updated properly, but the autocomplete predictions are not updated.

I have tried to use the virtual keyboard change callback to trigger a "keyup" (stackoverflow results), "keypress", "keydown", "change" and I even tried this (demo):

change : function(e, keyboard, el) {
    google.maps.event.trigger(autocomplete, 'place_changed');
}

which results in a javascript error basically showing that autocomplete.getPlace(); does not return a result.

So now I've tried the code below (in this demo), which uses the change callback to trigger an autocomplete prediction, but as you can see in that demo, the results differ.

change : function(e, keyboard, el) {
  var $el = $(el),
      service = new google.maps.places.AutocompleteService();
  if ($el.val() !== "") {
    service.getQueryPredictions({ input: $(el).val() }, function(predictions, status) {
      if (status != google.maps.places.PlacesServiceStatus.OK) {
        alert(status);
        return;
      }
      var list = '', $results = $('#results');
      for (var i = 0, prediction; prediction = predictions[i]; i++) {
        list += '<li>' + prediction.description + '</li>';
      }
      $results.html(list);
    });
  }
}

Ideally, I want to trigger the already established autocomplete prediction dropdown to update while typing on the virtual keyboard.

1条回答
唯我独甜
2楼-- · 2019-02-06 10:28

I found my answer (demo)!

change : function(e, keyboard, el) {
    google.maps.event.trigger( el, 'focus', {} );
}
查看更多
登录 后发表回答