我正在使用Google自動填充,並希望從網站上輸入的位置提取國家代碼(GB,IE,FR等)。Google Maps API Fetch國家/地區代碼
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;
正在返回該市/鎮所在的當地區域。
如何獲取國家/地區代碼?
謝謝大家對您對此事怎麼輸入,非常感謝;-)
感謝您的深3015.也許你可以對此有所瞭解?我從最初的腳本中嘗試了更多的東西,但在使用 document.getElementById(「country_from」)時我得不到相同的結果value = place.address_components [2] .short_name; 或 document.getElementById(「country_from」)。value = place.address_components [3] .short_name; 似乎方括號中的數字返回不同的值,例如倫敦:[1]大倫敦[2]英格蘭[3]英國,這是完美的。但是如果我將它應用到愛爾蘭的一個城鎮,同一級別[3]將不會返回任何結果。你知道爲什麼嗎?謝謝 – FusionDesign
「自動完成」結果因鍵入而異。如果你想看到不同輸入的輸出。你可以這樣做'console.log(JSON.stringify(autocomplete.getPlace()))'。在這個日誌中你可以看到國家發生的變量結果(在Json字符串中的位置)。因此,獲取確切的國家相關數據的方式我們無法預測發生的順序。在我的代碼中,我使用了'if(addressObj.types [j] ==='country')'這確保結果是針對鄉村類型的。希望這給出足夠的解釋 –