【问题标题】:Googlemaps places Autocomplete by className - JS loop Problem谷歌地图按类名放置自动完成 - JS循环问题
【发布时间】:2020-07-14 13:33:57
【问题描述】:

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

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

在本例中,autocomplete.addListener 上的 input[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 地图地点自动完成功能获取包含邮政编码的完整地址的最佳解决方案是什么?

【问题讨论】:

    标签: javascript jquery google-maps for-loop google-places-api


    【解决方案1】:

    解决此问题的一种方法是使用函数闭包,创建一个 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

    代码 sn-p:

    // 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 2013-01-02
      相关资源
      最近更新 更多