代码之家  ›  专栏  ›  技术社区  ›  user8718405

如何使用google api从所选国家/地区查找地址

  •  1
  • user8718405  · 技术社区  · 8 年前

    目前我正在使用google place api作为地址 我完全明白了

    但现在我想把它搬到特定的城市

    这是我的密码

    // Create the autocomplete object, restricting the search to geographical
    // location types.
    autocomplete = new google.maps.places.Autocomplete(
      (document.getElementById('autocomplete')),
        {types: ['geocode']});
    
    // When the user selects an address from the dropdown, populate the address
    // fields in the form.
    autocomplete.addListener('place_changed', fillInAddress);
    
    
    
     // 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;
              }
            }
          }
    

    output 现在我想要的是,如果我从选择框中选择“INDIA”,那么我的文本框中应该只显示印度地址

    有人知道如何限制这种行为吗

    2 回复  |  直到 8 年前
        1
  •  2
  •   moghya    8 年前

    在创建对象时添加对自动完成的限制。

    var options = {
      types: ['geocode'],
      componentRestrictions: {country: "IN"}
     };
    
    autocomplete = new google.maps.places.Autocomplete(
      (document.getElementById('autocomplete')),
        options);
    
    // When the user selects an address from the dropdown, populate the address
    // fields in the form.
    autocomplete.addListener('place_changed', fillInAddress);
    
    
    
     // 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;
              }
            }
          }
    

    随着国家价值的变化

    options.componentRestrictions.country
    
        2
  •  0
  •   MTK    8 年前

    您可以使用 componentRestrictions

    {types: ['geocode'],componentRestrictions: {country: 'IN'}}