如何获取城市名称以响应所选国家/地区?

时间:2016-06-03 15:18:08

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

我无需根据所选国家/地区获取城市名称。 我有来自数据库的国家/地区下拉列表。

默认情况下,用户可以从字段中选择城市,即没有限制。但是当他们选择国家时,城市的结果应该只能到达那个国家的城市。

    google.maps.event.addDomListener(window, 'load', intiGoogleLocation);
       function intiGoogleLocation() {
            var options = {
                types: ['(cities)']
            };
            if (typeof country !== 'undefined') {
                options.componentRestrictions = {country: country};
            }

            function fillInAddress() {
              //some custom logic
            }


        var input = document.getElementById('cities');
        var autocomplete = new google.maps.places.Autocomplete(input, options);
        autocomplete.addListener('place_changed', fillInAddress);
        }

所以问题是如何重置选项以便我可以将国家/地区设置为options.componentRestrictions

1 个答案:

答案 0 :(得分:2)

观察下拉菜单的change - 事件,并将自动填充的componentRestrictions设置为所需的值(基于所选的下拉项)



function intiGoogleLocation() {
  function fillInAddress() {
    //some custom logic
    console.log('place-name:'+this.getPlace().name);
  }

  var list          = document.getElementById('countries'),
      input         = document.getElementById('cities'),
      autocomplete  = new google.maps.places.Autocomplete(input, {
                types: ['(cities)']
      });
  
  google.maps.event.addListener(autocomplete,'place_changed', fillInAddress);
  
  google.maps.event.addDomListener(list,'change', function(e){
    
    var componentRestrictions={};
    
    if(this.value!==''){
      componentRestrictions.country=this.value
    }
    
    autocomplete.setComponentRestrictions(componentRestrictions);
    input.value='';
    if(e){
      autocomplete.set('place',{name:''});
    }
          
        
  });
  google.maps.event.trigger(list,'change',null);
}

<select id="countries">
  <option value="">any country</option>
  <option value="de">Germany</option>
  <option value="it">Italy</option>
  <option value="fr">France</option>
  <option value="gb">Great Britain</option>
</select>
<input id="cities"/>
<script src="https://maps.googleapis.com/maps/api/js?v=3&callback=intiGoogleLocation&libraries=places" async defer></script>
&#13;
&#13;
&#13;