我有以下代码,可使用google自动完成api从给定国家/地区查找城市:
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&sensor=false&libraries=places®ion=uk" type="text/javascript"></script>
function initialize() {
var input = document.getElementById('searchTextField');
var options = {
types: ['(cities)'],
componentRestrictions: { country: "uk" }
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window, 'load', initialize);
我已在脚本src中添加了区域,以便在输出中不包含国家/地区。
例如,如果输入Lo,则只会显示伦敦,而不会显示英国伦敦
但是,由于要从下拉列表中获取国家/地区的ISO代码,因此我需要能够更改componentRestrictions和google api URL中的区域。 任何想法如何做到这一点?我知道我可以从下拉菜单中选择以下国家:
var country= $('#CountryDropdown');
如何将var国家/地区传递给componentRestrictions和地区?
答案 0 :(得分:0)
我遇到了同样的问题,因此我解决了这个问题。 希望这会帮助你。
<script src="https://maps.googleapis.com/maps/api/js?key=Yourkey&v=3.exp&libraries=places"></script>
function initialize() {
var input = document.getElementById('FullAddress');
var options = {
types: ['address'],
componentRestrictions: { country: 'uk' }
};
autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
// document.getElementById(component).disabled = false;
}
$("#Latitude").val(place.geometry.location.lat());
$("#Longitude").val(place.geometry.location.lng());
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
});
}