Using Google Places Search Box. How to initiate a search by clicking a button?

血红的双手。 提交于 2019-12-03 12:36:12

You need to first trigger focus on the input element, then trigger a keydown event with code 13 (enter key).

var input = document.getElementById('target');

google.maps.event.trigger(input, 'focus')
google.maps.event.trigger(input, 'keydown', {
    keyCode: 13
});

JSFiddle demo

It is more simple than you think. With same starting point as above, https://developers.google.com/maps/documentation/javascript/examples/places-searchbox

Add a button to the HTML

<button id="button">click</button>

in initialize() add this to the very end, before } :

  var button = document.getElementById('button'); 
  button.onclick = function() {
    input.value='test';
    input.focus(); 
  }

input is already defined. All you have to do, to trigger the places search by a button is - really - to focus the input box associated with the searchBox. You dont have to mingle with searchBox or trigger "places_changed" or anything like that, which you can see elsewhere as suggestions - but in fact is not working.

I guess you want to trigger by a button "for some reason", like searching for some specific predifined - thats why I trigger the search with "test", simply by setting the input value to test.

Updated with working demo, based on the google example above -> http://jsfiddle.net/7JTup/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!