如何通过传递参数来添加工作场所自动完成

时间:2016-12-22 08:19:21

标签: javascript google-maps-api-3

我无法获得自动填充功能,所以我该怎么办?

                          points=108 (12x9)
                          lon : -16.5 to -11 by 0.5 degrees_east
                          lat : 12.5 to 16.5 by 0.5 degrees_north

js code:

<input class="form-control" name="loc[]" onkeypress="return initialize(input);" required>

1 个答案:

答案 0 :(得分:1)

您无需添加onkeypress事件,Autocomplete将为您处理。只需将input元素和一些options传递给Autocomplete构造函数。

示例:

var input = document.getElementById('searchTextField');
var options = {
  types: ['(cities)'],
  componentRestrictions: {country: 'us'}
};

autocomplete = new google.maps.places.Autocomplete(input, options);
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&libraries=places"></script>

<input id="searchTextField" type="text" size="50" placeholder="Cities in US">

- 更新 - 使用动态创建的input元素。

var form = document.getElementsByTagName('form')[0];
var options=[{placeholder:"Cities in US",options:{types:["(cities)"],componentRestrictions:{country:"us"}}},{placeholder:"Cities in FR",options:{types:["(cities)"],componentRestrictions:{country:"fr"}}}];

function addAutocomplete (elem, options) {
  autocomplete = new google.maps.places.Autocomplete(elem, options);
}

function crateAutoCompleteInputs ( count, optoins ) {
  for (var i = 0; i < count; i++) {
    var input = document.createElement('input');
    input.type = 'text';
    input.placeholder = optoins[i].placeholder;
    form.appendChild(input);
    addAutocomplete(input, options[i].options)
  }
}

crateAutoCompleteInputs(2, options)
input {
  margin-right: 12px;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&libraries=places"></script>

<form></form>