Googlemaps 按类名放置自动完成 - JS 循环问题

Googlemaps places Autocomplete by className - JS loop Problem

我需要通过 ClassName 为输入字段添加自动完成功能。我让它工作了,但是 Google 没有发回带有邮政编码的地址。

所以我尝试使用 addListener 在输入字段中插入 formatted_address。

在此示例中,autocomplete.addListener 上的输入 [i] 无效:

function initMap() {
 
    var input = $('.my_adresse'); 
    
    for (i = 0; i < input.length; i++) {
        var autocomplete = new google.maps.places.Autocomplete(input[i], {
            types: ['address'],
            componentRestrictions: {
                'country': ["de", "ch", "aut"]
            }
        });
        
        
        autocomplete.addListener('place_changed', function() {
            var place = autocomplete.getPlace();
            $(input[i]).val(place.formatted_address);
        });
    }          
} 

在此示例中,只有循环的最后一个元素起作用:

var input = $('.my_adresse'); 
    
    for (i = 0; i < input.length; i++) {
        var autocomplete = new google.maps.places.Autocomplete(input[i], {
            types: ['address'],
            componentRestrictions: {
                'country': ["de", "ch", "aut"]
            }
        }); 
        
        var input_to_change= input[i];

        autocomplete.addListener('place_changed', function() {
            var place = autocomplete.getPlace();
            $(input_to_change).val(place.formatted_address);
        });
    }          
} 

为什么我只得到循环的最后一个元素? 使用 Google 地图地点自动完成功能获取包含邮政编码的完整地址的最佳解决方案是什么?

解决该问题的一种方法是使用函数闭包,创建一个 createAutocomplete 函数来保持对输入和自动完成对象的闭包:

  function createAutocomplete(input, index) {
    var autocomplete = new google.maps.places.Autocomplete(input, {
      types: ['address'],
      componentRestrictions: {
        'country': ["de", "ch", "aut"]
      }
    });

    var input_to_change = input;

    autocomplete.addListener('place_changed', function() {
      var place = autocomplete.getPlace();
      console.log(place);
      $(input).val(place.formatted_address);
    });
  }

并在循环中调用它:

  for (i = 0; i < input.length; i++) {
    createAutocomplete(input[i], i);
  }

proof of concept fiddle

代码片段:

// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: -33.8688,
      lng: 151.2195
    },
    zoom: 13
  });
  var bounds = new google.maps.LatLngBounds();
  var input = $('.my_adresse');

  for (i = 0; i < input.length; i++) {
    createAutocomplete(input[i], i);
  }

  function createAutocomplete(input, index) {
    var autocomplete = new google.maps.places.Autocomplete(input, {
      types: ['address'],
      componentRestrictions: {
        'country': ["de", "ch", "aut"]
      }
    });

    var input_to_change = input;

    autocomplete.addListener('place_changed', function() {
      var place = autocomplete.getPlace();
      console.log(place);
      if (place != null) {
        $(input).val(place.formatted_address);
        if (place.geometry.location) {
          var marker = new google.maps.Marker({
            position: place.geometry.location,
            map: map,
            title: "" + index
          });
          bounds.extend(marker.getPosition());
          map.fitBounds(bounds);
        }
      }
    });
  }
}
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#map {
  height: 70%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pac-card" id="pac-card">
  <div>
    <div id="title">
      Autocomplete search
    </div>
  </div>
  <div id="pac-container">
    <input id="pac-input" class="my_adresse" type="text" placeholder="Enter a location">
  </div>
  <div>
    <input class="my_adresse" type="text" placeholder="Enter a location">
  </div>
  <div>
    <input class="my_adresse" type="text" placeholder="Enter a location">
  </div>
  <div>
    <input class="my_adresse" type="text" placeholder="Enter a location">
  </div>
</div>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>