我正在使用Google自动填充功能,并希望从网站上输入的位置提取国家/地区代码(GB,IE,FR等)。
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
document.getElementById("orig_latitude").value= place.geometry.location.lat();
document.getElementById("orig_longitude").value= place.geometry.location.lng();
document.getElementById("country_from").value = place.address_components[1].short_name;
} else {
me.destinationPlaceId = place.place_id;
document.getElementById("dest_latitude").value= place.geometry.location.lat();
document.getElementById("dest_longitude").value= place.geometry.location.lng();
document.getElementById("country_to").value = place.address_components[2].short_name;
}
me.route();
});
};
不幸的是
place.address_components [1] .short_name;
返回这个城市/城镇所在的地区。
如何获取国家/地区代码?
感谢大家对此事的意见,非常感谢; - )
答案 0 :(得分:1)
有关详细信息,请参阅Google的Place Autocomplete
Fiddle演示
JS代码:
var input = document.getElementById('searchTextField');
var options = {
types: ['geocode']
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
for (var i = 0; i < place.address_components.length; i += 1) {
var addressObj = place.address_components[i];
for (var j = 0; j < addressObj.types.length; j += 1) {
if (addressObj.types[j] === 'country') { /*outputs result if it is country*/
document.getElementById('country_shortName').innerHTML = addressObj.short_name
}
}
}
});
HTML
<label for="searchTextField">Please Insert an address:</label>
<br>
<input id="searchTextField" type="text" size="50">
<p >Country Short Code: <span id="country_shortName"></span></p>
答案 1 :(得分:0)
谢谢Deep 3015.我使用了您的解决方案,它确实有效!奇妙...
请注意可能遇到同样问题的其他用户:
I had to replace .innerHTML with .value to make it work
除此之外,现在100%工作。再次感谢您的帮助[竖起大拇指]