Google 地图 API 获取国家代码

Google Maps API Fetch Country Code

我正在使用 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;

正在返回此city/town所在的本地区域。

如何获取国家代码?

感谢大家对此事的投入,非常感谢;-)

有关详细信息,请参阅 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>

感谢 Deep 3015。我使用了您的解决方案,它确实有效!太棒了...

可能遇到相同问题的其他用户请注意:

I had to replace .innerHTML with .value to make it work

除此之外,现在工作 100%。再次感谢您的帮助[竖起大拇指]