两个搜索字段需要 google 个位置 API

Need google places API for two search fields

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

我试过使用 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>

您可能必须为所有输入初始化自动完成,在您的情况下 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>