【问题标题】:Need google places API for two search fields需要两个搜索字段的Google Places API
【发布时间】:2019-12-20 16:09:20
【问题描述】:

我正在构建一个表单,希望用户在其中添加他们的出发地和目的地。 它将是邮政编码到邮政编码。我有点新手,所以我按照指南进行操作,能够使一个输入字段起作用,但不能使另一个输入字段起作用。

我尝试使用 getElementsByClassName


<form style="float:right;" name='ap_form_9946' id="regForm" method="post" action=''>

        <div class="tab">

    <label>Where are you moving from?</label>
          <p><input type="text" autocomplete="off" id="zipcode" placeholder="Zipcode origin" name="75990"></p>

          <label>Where are you moving to?</label>
          <p><input type="text" name="75991" id="zipcode2" placeholder="Zipcode Destination"></p>

        </div>

   </form>

    <script>
    function activatePlacesSearch(){
        var input = document.getElementById('zipcode')
        var autocomplete = new google.maps.places.Autocomplete(input);
    }
    </script>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=hiBOnpYTFR3wI7Th-dI9OT8xtSGUw0lMZ74&libraries=places&callback=activatePlacesSearch"></script>

【问题讨论】:

    标签: javascript html api autocomplete zipcode


    【解决方案1】:

    您可能需要为所有输入初始化自动完成功能,在您的情况下为 zipcodezipcode2,您可以使用 document.querySlectorAll 来执行此操作:

    <form name='ap_form_9946' id="regForm" method="post" action=''>
    
      <div class="tab">
    
        <label>Where are you moving from?</label>
        <p><input type="text" autocomplete="off" id="zipcode" placeholder="Zipcode origin" name="75990"></p>
    
        <label>Where are you moving to?</label>
        <p><input type="text" name="75991" id="zipcode2" placeholder="Zipcode Destination"></p>
    
      </div>
    
    </form>
    
    <script>
      function activatePlacesSearch() {
        var inputs = document.querySelectorAll('#zipcode, #zipcode2');
        var autocompletes = [];
        inputs.forEach(input => {
          autocompletes.push(new google.maps.places.Autocomplete(input));
        });
      }
    </script>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=activatePlacesSearch"></script>

    【讨论】:

    • @AdamNoah 很高兴我能帮上忙!
    猜你喜欢
    • 2011-08-21
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    • 2013-12-14
    • 1970-01-01
    • 2016-05-24
    相关资源
    最近更新 更多