我想要有3个盒子来使用谷歌API的javascript来填充地址时提供建议。但不幸的是它仅适用于1个文本框基地city.Other两个不响应javascript
的Javascript
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places&language=en-AU"></script>
<script>
var autocomplete = new google.maps.places.Autocomplete($("#loc")[0], {});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
console.log(place.address_components);
});
</script>
</script>
&#13;
<div class="form-group">
<label class="col-md-3 control-label" for="example-text-input">Base City</label>
<div class="col-md-3">
<input type="text" id="loc" name="City" class="form-control" >
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="example-text-input">Base Location</label>
<div class="col-md-3">
<input type="text" id="loc" name="Location" class="form-control" >
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="example-text-input">Work Location</label>
<div class="col-md-3">
<input type="text" id="loc" name="Work_Location" class="form-control" >
</div>
</div>
&#13;
答案 0 :(得分:0)
问题是你有三个div具有相同的id =“loc”;但是,id应该是唯一的。因此,当您运行代码时,一旦编译器看到它使用它的第一个id,它就不会进一步搜索下一个。
要解决此问题,您需要为每个div提供不同的id,并为每个div创建自动完成变量。您也可以创建单独的侦听器,但我将其留给您。
var autocomplete1 = new google.maps.places.Autocomplete($("#loc1")[0], {});
var autocomplete2 = new google.maps.places.Autocomplete($("#loc2")[0], {});
var autocomplete3 = new google.maps.places.Autocomplete($("#loc3")[0], {});
google.maps.event.addListener(autocomplete1, 'place_changed', function () {
var place = autocomplete1.getPlace();
console.log(place.address_components);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places&language=en-AU"></script>
<body>
<div class="form-group">
<label class="col-md-3 control-label" for="example-text-input">Base City</label>
<div class="col-md-3">
<input type="text" id="loc1" name="City" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="example-text-input">Base Location</label>
<div class="col-md-3">
<input type="text" id="loc2" name="Location" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="example-text-input">Work Location</label>
<div class="col-md-3">
<input type="text" id="loc3" name="Work_Location" class="form-control">
</div>
</div>
</body>
答案 1 :(得分:0)
function initialize() {
//debugger;
// Create the autocomplete object, restricting the search
// to geographical location types.
var clsname = document.getElementsByClassName('autocomplet');
for (var i = 0; i < clsname.length; i++) {
var id = clsname[i].id;
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById(id)), {
types: ['geocode']
});
}
}