谷歌地图 - 点击按钮时触发搜索框

Cos*_* SD 7 javascript google-maps google-maps-api-3

我有兴趣实施一个Google地图搜索按钮,旁边有一个"提交"/"开始"按钮(例如http://maps.google.com上).如果我在搜索框中按Enter键,一切都很好,但我不知道如何使用按钮强制/提交搜索.

现在我的代码基于以下示例:https://developers.google.com/maps/documentation/javascript/examples/places-searchbox.最重要的部分是我现在正在使用它:

HTML:

<div id="intro-search">
    <input id="search-box" />
    <button type="button">Submit!</button>
</div>
Run Code Online (Sandbox Code Playgroud)

JS:

  // Listen for the event fired when the user selects an item from the
  // pick list. Retrieve the matching places for that item.
  google.maps.event.addListener(searchBox, 'places_changed', function() {
    // ... 
    // Show the results on the map
    // ...
  }
Run Code Online (Sandbox Code Playgroud)

我不知道如何在按钮点击时触发相同的操作.

另一方面,SearchBox自动完成控件有什么区别?他们不做同样的事情吗?

Ale*_*min 10

对于SearchBox,您必须在输入字段上使用谷歌地图的触发事件,如此

document.getElementById('my-button').onclick = function () {
    var input = document.getElementById('my-input');

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

};
Run Code Online (Sandbox Code Playgroud)


小智 5

为了建立在 Alex Beauchemin 和 Scott Butler 的答案的基础上,今天(但将来可能不会)对我有用的非 Angular、非 jQuery 选项是:

document.getElementById('my-button').onclick = function () {
  var input = document.getElementById('my-input');

  function noop() {}

  google.maps.event.trigger(input, 'focus', {});
  google.maps.event.trigger(input, 'keydown', {
    keyCode: 40, // arrow down
    stopPropagation: noop, // because these get called
    preventDefault: noop,
  });  
  google.maps.event.trigger(input, 'keydown', { keyCode: 13 });  // enter
  google.maps.event.trigger(this, 'focus', {});
};
Run Code Online (Sandbox Code Playgroud)