【问题标题】:How to get the country code from Google Places API如何从 Google Places API 获取国家代码
【发布时间】: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&amp;libraries=places&callback=initAutocomplete"
    async defer></script>

【问题讨论】:

    标签: javascript google-maps-api-3


    【解决方案1】:

    终于找到了在google search 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',
      political: '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);
    }
    
    // [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]];
            if(place.address_components[i][componentForm['political']]){
                console.log(place.address_components[i][componentForm['country']]);
                if(isNaN(place.address_components[i][componentForm['political']])){
                    country_code=place.address_components[i][componentForm['political']];
                    var country_name=place.address_components[i][componentForm['country']];
                }
            }
          document.getElementById(addressType).value = val;
    
        }
      }
      // **Country code, Country name goes here**
      document.getElementById("Country_code").value=country_code;
      document.getElementById("Country_name").value=country_name;
      console.log('Country Code='+country_code+', Country Name='+country_name);
    }
    // [END region_fillform]
    
        </script>
        <script src="https://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places&callback=initAutocomplete"
            async defer></script>
    

    【讨论】:

      【解决方案2】:

      要获取国家代码,请获取地址组件的短名称,类型为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;
      } 
      

      代码 sn-p:

      // 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>

      【讨论】:

        【解决方案3】:
        <?php
        $address = '77-379 North End road, London London SW61NP, United Kingdom'; // Your address(Please USe exist address)
        $prepAddr = str_replace(' ','+',$address);
        
        $geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&key=AIzaSyDUpz-WEZ7r24PPkGKEuyqBd9VsPPVPcQk&sensor=false');
        $output= json_decode($geocode);
        
        
        if ( isset($output->results) ) {
            if ( isset($output->results[0]) ) {
                if ( isset($output->results[0]->address_components) ) {
                    foreach ($output->results[0]->address_components as $key => $value) {   
                        if ( isset($value->types) ) {
                            if ( isset($value->types[0]) ) {
                                if($value->types[0] == 'country'){
                                    print_r($value->short_name); //GB
                                }
                            }
                        }
                    }
                }
            }
        } ?>
        

        【讨论】:

          【解决方案4】:

          使用以下功能,您将获得邮政编码、国家、州、城市等。

          export let placeAddresCompoponent = {
              ZIP_CODE: 'postal_code',
              COUNTRY: 'country',
              STATE: 'administrative_area_level_1',
              CITY: 'administrative_area_level_2',
              TOWN: 'sublocality_level_1',
              AREA: 'sublocality_level_2',
              NEAREST_ROAD: 'route'
          }
          

          使用以下函数从地址组件中获取数据。您将从 Google Place Api 的结果中获得 address_components

          export function getAddressComponent(address_components, key) {
              var value='';
              var postalCodeType = address_components.filter(aComp =>
                  aComp.types.some(typesItem => typesItem === key))
              if (postalCodeType != null && postalCodeType.length > 0)
                  value = postalCodeType[0].long_name
              return value;
          }
          

          您可以使用下面的方式获取特定的地址组件。

          addressComponent = 来自 google place api 结果的 address_components 数组

          var zipCode = getAddressComponent(addressComponent, placeAddresCompoponent.ZIP_CODE)
          var country = getAddressComponent(addressComponent, placeAddresCompoponent.COUNTRY)
          console.log('zipCode : ', zipCode)
          console.log('country : ', country)
          

          【讨论】:

          • 嗨,当我向 google place api 发送带有字段的请求时:['address_components'] 我有一个错误:“解析'fields'参数时出错:不支持的字段名称'address_components'。”,我需要做什么才能启用该选项?
          • 完美。虽然对于城市,我发现locality 对我来说更准确,administrative_area_level_2 有时为空
          【解决方案5】:

          // 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: 'long_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>

          【讨论】:

            【解决方案6】:
            <vue-google-autocomplete required="" id="p-map" v-model="address" ref="address" classname="form-control" placeholder="Enter delivery address" v-on:placechanged="getAddressData">
                                                    </vue-google-autocomplete>
            
            getAddressData: function (_addressData, placeResultData) {
                   const country = placeResultData.address_components.find(ad => ad.long_name === _addressData.country);
                   const country_code = country.short_name
                   console.log(country_code)
                }
            

            如果您使用的是 vue-google-autocomplete 插件,这是一种方法

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-03-09
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多