google-maps - 谷歌自动完成分为单独的字段

标签 google-maps google-maps-api-3 geolocation google-places-api

嗨,我有 3 个不同的输入(城市、街道和街道编号)。例如,我的国家是“波兰”,城市是“华沙”,所以我只需要显示这个城市的街道。怎么做?

var input = document.getElementById('inputid');

var param = {
    componentRestrictions: {country: 'PL'},
};

autocomplete = new google.maps.places.Autocomplete(input, param);
geocoder = new google.maps.Geocoder();

google.maps.event.addListener(autocomplete, 'place_changed', function() {
    var place = autocomplete.getPlace();
    if(place.address_components) {
        console.log(place.address_components);
    }
});

最佳答案

这个很简单。如果您使用的是 Google Place Autocomplete Address Form 中的示例代码,您所需要做的就是删除不必要的输入字段,只保留您想要填充的字段 - 例如:街道编号和路线。您还需要删除不必要的属性,只保留 componentForm 对象中的 street_number 和路线。像这样:

var componentForm = {
 street_number: 'short_name',
 route: 'long_name'
};

自动完成对象的第二个参数(选项)中的“componentRestrictions”等其他选项。它应该看起来像这样:

autocomplete = new google.maps.places.Autocomplete(
   (document.getElementById('autocomplete')),
     {
       types: ['geocode'],
       componentRestrictions : {
        country: 'PL',
       }
     }
);

有关组件过滤的更多详细信息,您可以查看 this 链接。

另请注意这一点:

The selection of specific address components in this example is based on a typical address format. You may need to select different components to align with the postal address formats of different countries.

了解更多请关注this 链接。

这是一个现场演示:

      var placeSearch, autocomplete;
      var componentForm = {
        street_number: 'short_name',
        route: '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: ['geocode'],
              componentRestrictions : {
                 country: 'PL',
              }
            }
        );

        // When the user selects an address from the dropdown, populate the address
        // fields in the form.
        autocomplete.addListener('place_changed', fillInAddress);
      }

      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;
          }
        }
      }

      // Bias the autocomplete object to the user's geographical location,
      // as supplied by the browser's 'navigator.geolocation' object.
      function geolocate() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var geolocation = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
            var circle = new google.maps.Circle({
              center: geolocation,
              radius: position.coords.accuracy
            });
            autocomplete.setBounds(circle.getBounds());
          });
        }
      }
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&libraries=places&callback=initAutocomplete"
        async defer></script>
            <div id="locationField">
      <input id="autocomplete" placeholder="Enter your address"
             onFocus="geolocate()" type="text"></input>
    </div>

    <table id="address">
      <tr>
        <td class="label">Street address</td>
        <td class="slimField"><input class="field" id="street_number"
              disabled="true"></input></td>
        <td class="wideField" colspan="2"><input class="field" id="route"
              disabled="true"></input></td>
      </tr>
    </table>

希望对你有帮助!

关于google-maps - 谷歌自动完成分为单独的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46826186/

相关文章:

javascript - JQuery - 将 Google map 放在 "content"中不可见吗?

android-emulator - Android Geolocation 无法在模拟器中获取您的位置错误

android - 将 Google map 数据集成到游戏中。如何?

javascript - 使用 JavaScript 在 Google map 中叠加多个图像

google-maps - Google 地方信息自动完成

javascript - 如何根据最接近输入地址的纬度/经度显示内容

javascript - 如何显示From地址到To地址的方向

google-maps - React Native Maps-新定价

Javascript 地理定位无法在更新的 Android chrome 上运行

javascript - 地理位置在 x 次尝试后挂起,在浏览器重新启动后有效