0

我需要 Google Place Autocomplete 这些值:

alert(
  place.name +                       // Works
  place.geometry.location.lat() +    // Works
  place.country +  // Not works - what is correct value to get country value?
  place.state      // Not works - what is correct value to get state value?
  );

适用于 place.nameplace.geometry,但不适用于place.countryplace.state

如何获得其他两个值?谢谢你的任何建议。

整体功能:

function initializeGoogleMaps() {
    var input = document.getElementById("googleMapsSearch");
    var autocomplete = new google.maps.places.Autocomplete(input);
     google.maps.event.addListener(
        autocomplete,
        "place_changed",
        function() {
        var place = autocomplete.getPlace();
        alert(
          place.name +                       // Works
          place.geometry.location.lat() +    // Works
          place.country +  // Not works - what is correct value to get country value?
          place.state      // Not works - what is correct value to get state value?
        );
        document.getElementById("city").value = place.name;   // Works
        document.getElementById("cityLat").value = place.geometry.location.lat();   // Works
        document.getElementById("country").value = place.country;   // Not works
        document.getElementById("state").value = place.state;   // Not works
     });
}
4

1 回答 1

0

可以address_components在方法返回的数组下获取州和国家getDetails()。由于地址组件作为数组返回,因此您可以像这样解析结果:

var country;
var state;
var components = place.address_components;

   for(i=0;i<components.length;i++){
       if(place.address_components[i].types[0].toString() === 'administrative_area_level_1'){
          state = place.address_components[i].long_name;
       }else if(place.address_components[i].types[0].toString() === 'country'){
           country = place.address_components[i].long_name;
           } 
     }

注意:administrative_area_level_1通常表示state并且根据某个国家的政治等级而有所不同。

这是您可以参考的完整示例。您只需将“YOUR_API_KEY”替换为您自己的 API 密钥。

有关地点详情结果的更多信息,请查看此链接:https ://developers.google.com/maps/documentation/javascript/places#place_details_results

希望这可以帮助!

于 2020-05-26T03:55:22.257 回答