【发布时间】:2016-02-26 12:08:41
【问题描述】:
我正在尝试使用 HTML 5 GeoLocation 获取经度和纬度,然后使用 Google Maps API 获取该经度/纬度的国家代码。有没有更简单的方法可以从 google places api 获取国家代码?
我从这个链接找到了解决方案 ==> Getting country code from Google Maps and HTML 5 GeoLocation 获取国家代码。
有没有办法直接从谷歌地方 api 获取国家代码,而无需先获取纬度和经度,然后传递给谷歌地图 api。
这是我用来从 google places api 获取国家/地区代码的以下脚本
<script>
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
{types: ['(cities)']});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
//autocomplete.addListener('place_changed', fillInAddress);
// Get Latitude and longitude
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
//document.getElementById('city2').value = place.name;
document.getElementById('lat').value = place.geometry.location.lat();
document.getElementById('lng').value = place.geometry.location.lng();
});
}
// [START region_fillform]
function fillInAddress() {
// 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;
}
// 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;
}
}
}
// [END region_fillform]
</script>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&callback=initAutocomplete"
async defer></script>
【问题讨论】:
标签: javascript google-maps-api-3