javascript - 如何从 Google Places API 获取国家代码

标签 javascript google-maps-api-3

我正在尝试使用 HTML 5 GeoLocation 获取经度和纬度,然后使用 Google Maps API 获取该经度/纬度的国家/地区代码。有没有更简单的方法从 google places api 获取国家代码?

我从这个链接找到了解决方案 ==> Getting country code from Google Maps and HTML 5 GeoLocation 获取国家代码。

有没有办法直接从 google places api 获取国家代码,而无需先获取经纬度然后再传递给 google maps 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&amp;libraries=places&callback=initAutocomplete"
    async defer></script>

最佳答案

要获取国家代码,请获取类型为 country 的地址组件的简称:

// for the country, get the country code (the "short name") also
if (addressType == "country") {
  document.getElementById("country_code").value = place.address_components[i].short_name;
} 

代码片段:

// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
  }

  // 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;
    }
    // for the country, get the country code (the "short name") also
    if (addressType == "country") {
      document.getElementById("country_code").value = place.address_components[i].short_name;
    }
  }
}

var placeSearch, autocomplete;
var componentForm = {
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_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.
  // Get Latitude and longitude
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
    var place = autocomplete.getPlace();
    document.getElementById('lat').value = place.geometry.location.lat();
    document.getElementById('lng').value = place.geometry.location.lng();
    fillInAddress();
  });
}
google.maps.event.addDomListener(window, 'load', initAutocomplete);
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="locationField">
  <input id="autocomplete" placeholder="Enter your address" type="text" />
</div>
<table id="address">
  <tr>
    <td class="label">City</td>
    <td class="wideField" colspan="3">
      <input class="field" id="locality" disabled="true" />
    </td>
  </tr>
  <tr>
    <td class="label">State</td>
    <td class="slimField">
      <input class="field" id="administrative_area_level_1" disabled="true" />
    </td>
  </tr>
  <tr>
    <td class="label">Country</td>
    <td class="wideField" colspan="2">
      <input class="field" id="country" disabled="true" />
    </td>
    <td class="label">Country Code</td>
    <td class="shortField">
      <input class="field" id="country_code" disabled="true" />
    </td>
  </tr>
  <tr>
    <td class="label">latitude</td>
    <td class="wideField" colspan="3">
      <input class="field" id="lat" disabled="true" />
    </td>
  </tr>
  <tr>
    <td class="label">longitude</td>
    <td class="wideField" colspan="3">
      <input class="field" id="lng" disabled="true" />
    </td>
  </tr>
</table>

关于javascript - 如何从 Google Places API 获取国家代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33887081/

相关文章:

javascript - 如果我在每个 css 和 js 文件上使用 .min 方法来保护我的代码,这正常吗?

javascript - 在发送到后端时显示数据

javascript - 创建带有成功/错误的 promise ,例如 ajax

javascript - Bootstrap Modal 中谷歌地图的灰色 map

google-maps - 标记群集-融合表层-Google Maps v3

javascript - 如何读取 JSON 以从 YouTube 获取最后一个视频

javascript - 如何将实际对象(即对象的引用)传递给指令?

google-maps - 自定义谷歌地图 landscape.man_made 颜色并保持阴影?

android - 在谷歌地图android中使用gps移动标记

java - 安卓谷歌地图 : how to remove an overlay from the map?