Google Maps API - 自动填写英国郡

时间:2017-07-15 11:40:10

标签: javascript html google-maps

我正在使用Google地址自动完成API,使用Google提供的标准示例代码格式化内部应用的地址:

https://google-developers.appspot.com/maps/documentation/javascript/examples/full/places-autocomplete-addressform

我正确地为每个邮政编码得到类似于以下的回复:

   "html_attributions" : [],
   "result" : {
      "address_components" : [
         {
            "long_name" : "BA1 1UN",
            "short_name" : "BA1 1UN",
            "types" : [ "postal_code" ]
         },
         {
            "long_name" : "Bath",
            "short_name" : "Bath",
            "types" : [ "postal_town" ]
         },
         {
            "long_name" : "Bath and North East Somerset",
            "short_name" : "Bath and North East Somerset",
            "types" : [ "administrative_area_level_2", "political" ]
         },
         {
            "long_name" : "England",
            "short_name" : "England",
            "types" : [ "administrative_area_level_1", "political" ]
         },
         {
            "long_name" : "United Kingdom",
            "short_name" : "GB",
            "types" : [ "country", "political" ]
         }

除了“administrative_area_level_2”(即县)之外,我的所有表单字段都完好无损。我的工作HTML看起来像这样:

<div class="form-group">
    <label>Postal Town</label>
    <input class="form-control field" placeholder="Enter your country" 
    required="true" name="postal_town" id="postal_town">
    <p class="help-block">Enter your country.</p>
</div>

但这不是:

<div class="form-group">
    <label>County</label>
    <input class="form-control field" placeholder="Enter your county" required="true" name="administrative_area_level_2" id="administrative_area_level_2">
    <p class="help-block">Enter your county.</p>
</div>

如何访问该字段以自动填写表单?

1 个答案:

答案 0 :(得分:0)

有时走开并拥有新鲜的眼睛很好。非常简单的修复,标准的Google自动完成功能具有以下代码:

          var placeSearch, autocomplete;
          var componentForm = {
            street_number: 'short_name',
            route: 'long_name',
            postal_town: 'long_name',
            administrative_area_level_1: 'short_name',
            country: 'long_name',
            postal_code: 'short_name'
          };

您只需要包含附加字段,代码如下:

          var placeSearch, autocomplete;
          var componentForm = {
            street_number: 'short_name',
            route: 'long_name',
            postal_town: 'long_name',
            administrative_area_level_1: 'short_name',
            administrative_area_level_2: 'short_name',
            country: 'long_name',
            postal_code: 'short_name'
          };

现在它自动填充表单,我没试过但是假设它也适用于其他字段。爱谷歌!