简体   繁体   English

Google商家信息自动填充功能不适用于动态生成的输入元素

[英]Google Places Autocomplete doesn't work on dynamically generated input elements

autocomplete works perfectly on multiple static input fields. 自动完成功能在多个静态输入字段上完美运行。 But when i add an input field by button autocomplete doesn't work on these input fields. 但是当我通过按钮添加输入字段时,自动完成功能对这些输入字段不起作用。 Maybe the problem is in closure, but I'm not sure because of my weak Javascript. 也许问题是关闭,但我不确定,因为我的弱Javascript。 Can anyone help me? 谁能帮我?

Here is the code: 这是代码:

<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script>
var map = null;
var marker = [];
var autocomplete = [];
var inputs = [];
var types = [];
var autocompleteOptions = {
 componentRestrictions: {country: "az"}
};

This function dynamically creates up to 5 input fields(I put this function in initialize method and it diidn't work either): 这个函数动态创建最多5个输入字段(我把这个函数放在初始化方法中,它也不起作用):

$(document).ready(function(){
var count = 2;
$("#addInputField").click(function(){
    count++;
    $("#inputlar").append("<input id='pac-input" + count + "' class='controlsInput' type='text' placeholder='Enter your destination' /> <br />");
    var newInput = [];
    var newEl = document.getElementById('pac-input' + count);
    newInput[count-1] = newEl;
    setupAutocomplete(autocomplete, newInput, count-1);
    if (count === 7) {
        $("#addInputField").remove();
    }
});    

}); });

This function is called from initialize method for maintaininng autocomplete on multiple inputs. 从初始化方法调用此函数,以便在多个输入上维护自动完成。 Works perfectly: 完美的工作:

function setupAutocomplete(autocomplete,inputs,i) {

        autocomplete[i] = new google.maps.places.Autocomplete(inputs[i], autocompleteOptions);
        autocomplete[i].bindTo('bounds', map);

        google.maps.event.addListener(autocomplete[i], 'place_changed', function() {
          var infowindow = new google.maps.InfoWindow();
          if (marker[i] && marker[i].setMap) {
             marker[i].setMap(null);
             marker[i] = null;
          }
          marker[i] = new google.maps.Marker({
                map: map
          });  
          infowindow.close();
          marker[i].setVisible(false);
          var place = autocomplete[i].getPlace();
          if (!place.geometry) {
            return;
          }

          // If the place has a geometry, then present it on a map.
          if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
          } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17);  // Why 17? Because it looks good.
          }

          marker[i].setPosition(place.geometry.location);
          marker[i].setVisible(true);

          var address = '';
          if (place.address_components) {
            address = [
              (place.address_components[0] && place.address_components[0].short_name || ''),
              (place.address_components[1] && place.address_components[1].short_name || ''),
              (place.address_components[2] && place.address_components[2].short_name || '')
            ].join(' ');
          }

          infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
          infowindow.open(map, marker[i]);
        });
    }

And finaly initialize method: 并最终初始化方法:

 function initialize() {
      var mapOptions = {
        center: new google.maps.LatLng(40.4700, 50.0000),
        zoom: 10,
        zoomControl:true,
        zoomControlOptions: {
          style:google.maps.ZoomControlStyle.SMALL
        },
        mapTypeControl:true,
        mapTypeControlOptions: {
          style:google.maps.MapTypeControlStyle.DROPDOWN_MENU 
        }
      };
      map = new google.maps.Map(document.getElementById('map-canvas'),
        mapOptions);
      types = document.getElementById('type-selector');
      map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);


      inputs = document.getElementsByClassName("controlsInput");
      for(var i = 0; i < inputs.length; i++) {  
       setupAutocomplete(autocomplete,inputs,i);
      }
      // Sets a listener on a radio button to change the filter type on Places
      // Autocomplete.
      function setupClickListener(id, types) {
        var radioButton = document.getElementById(id);
        google.maps.event.addDomListener(radioButton, 'click', function() {
          for (var i=0 ; i<autocomplete.length; i++) {
            autocomplete[i].setTypes(types);
          }
        });
      }

      setupClickListener('changetype-all', []);
      setupClickListener('changetype-establishment', ['establishment']);
      setupClickListener('changetype-geocode', ['geocode']);
    }

    google.maps.event.addDomListener(window, 'load', initialize);

</script>
</head>

And the HTML: 和HTML:

<body>
    <table>
                <tr>
                    <td>
                        <div>
                            <div id="inputlar">
                            <input id="pac-input" class="controlsInput" type="text" placeholder="Marşrutunuzu haradan başlayırsınız" /> <br />
                            <input id="pac-input2" class="controlsInput" type="text" placeholder="Haraya gedirsiniz"> <br />
                            </div>  <br />
                            <input id="addInputField" type="button" value="Yolüstü dayanacaq əlavə et" class="styled-button-10"/>

                            <div hidden="hidden" id="type-selector" class="controls">
                              <input type="radio" name="type" id="changetype-all" checked="checked">
                              <label for="changetype-all">All</label>

                              <input type="radio" name="type" id="changetype-establishment">
                              <label for="changetype-establishment">Establishments</label>

                              <input type="radio" name="type" id="changetype-geocode">
                              <label for="changetype-geocode">Geocodes</label>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div id="map-canvas" style="width:540px;height:380px;"></div>
                    </td>
                </tr>
            </table>
</body>
</html>

Problem is that you don't call setupAutocomplete() after new elements are added. 问题是在添加新元素后不要调用setupAutocomplete() You have to do something like this (could be improved using jQuery): 你必须做这样的事情(可以使用jQuery进行改进):

$(document).ready(function(){
    var count = 2;
    $("#addInputField").click(function(){
        count++;
        console.log('add new input field');
        $("#inputlar").append("<input id='pac-input" + count + "' class='controlsInput' type='text' placeholder='Enter your destination' /> <br />");

        // added
        var newInput = [];
        var newEl = document.getElementById('pac-input' + count);
        newInput.push(newEl);
        setupAutocomplete(autocomplete, newInput, 0);

        if (count === 7) {
            $("#addInputField").remove();
        }
    });    
});

Update: example at jsbin . 更新: jsbin上的示例 setupAutocomplete() has to be changed a little, commented code left there to see difference, idx used instead of parameter i . setupAutocomplete()必须改变一点,注释代码留在那里看看差异, idx用来代替参数i

function setupAutocomplete(autocomplete, inputs, i) {

    // autocomplete[i] = new google.maps.places.Autocomplete(inputs[i], autocompleteOptions);
    autocomplete.push(new google.maps.places.Autocomplete(inputs[i], autocompleteOptions));
    var idx = autocomplete.length - 1;
    //autocomplete[i].bindTo('bounds', map);
    autocomplete[idx].bindTo('bounds', map);

    //google.maps.event.addListener(autocomplete[i], 'place_changed', function() {
    google.maps.event.addListener(autocomplete[idx], 'place_changed', function() {
    ...

Note: I didn't check what will happen when you reach 7 autocomplete inputs. 注意:我没有检查当您达到7个自动完成输入时会发生什么。 Maybe you will have to do some update. 也许你将不得不做一些更新。

I have developed script which gives Google place search input for start location, end location and as well for waypoints and it is pretty If you try for once. 我已经开发了脚本,可以为开始位置,结束位置以及路标提供Google地方搜索输入,如果您尝试一次,它就很漂亮了。 Here is the code. 这是代码。 Download it and run in any browser and Enjoy..! 下载并在任何浏览器中运行并享受..!

Google directions with waypoints search waypoints 使用航点的Google方向搜索航点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM