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

后端 未结 2 1168
小蘑菇
小蘑菇 2021-02-14 17:24

Either I am an idiot or this was an egregious oversight on the part of the Google Maps team.

I am attempting to trigger a places search request on a button click event i

相关标签:
2条回答
  • 2021-02-14 17:52

    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

    0 讨论(0)
  • 2021-02-14 17:53

    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/

    0 讨论(0)
提交回复
热议问题