0

我寫了一個小函數,它將使用google.maps.event.addListener()來獲取用戶地址。這裏是jsFiddle只顯示google.maps.event.addListener()中的街道地址

一切都正是我想要的,除了當用戶完成打字並從street字段集中出來時,我只想要input中的街道地址。

目前,它看起來像這樣:

now

但我希望它是這樣的:

enter image description here

感謝已經尋求幫助。乾杯。

回答

3

使用短延遲申請的StreetAddress

setTimeout(function(){$('#address').val(streetAddress);},50); 
2

上述解決方案的偉大工程,以自動完成單獨的地址字段。這裏有一個選項偏好結果的實現,但是我有問題使用邊界來偏見自動填充字段的結果。這是我的jsFiddle

var defaultBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(33.89028890,-117.5617340), 
    new google.maps.LatLng(33.7706850,-117.6639850) 
); 

var updateAddress = { 
    autocomplete: new google.maps.places.Autocomplete($("#address")[0], { 
     bounds: defaultBounds, 
     types: ['geocode'], 
     componentRestrictions: {country: 'us'} 
    }),    
    event: function(){ 
     var self = this;  
     google.maps.event.addListener(self.autocomplete, 'place_changed', function() { 
      var place = self.autocomplete.getPlace(), 
       address = place.address_components, 
       streetAddress = '', 
       suburb = '', 
       state = '', 
       zip = '', 
       country = ''; 

      for (var i = 0; i < address.length; i++) { 
       var addressType = address[i].types[0]; 

       if (addressType == 'subpremise') { 
        streetAddress += address[i].long_name + '/'; 
       } 
       if (addressType == 'street_number') { 
        streetAddress += address[i].long_name + ' '; 
       } 
       if (address[i].types[0] == 'route') { 
        streetAddress += address[i].long_name; 
       } 
       if (addressType == 'locality') { 
        suburb = address[i].long_name; 
       } 
       if (addressType == 'administrative_area_level_1') { 
        state = address[i].long_name; 
       } 
       if (addressType == 'postal_code') { 
        zip = address[i].long_name; 
       } 
       if (addressType == 'country') { 
        country = address[i].long_name; 
       } 
      } 

      // update the textboxes 
      setTimeout(function(){$('#address').val(streetAddress);},50); 
      $('#suburb').val(suburb); 
      $('#state').val(state); 
      $('#zip').val(zip); 
     }); 

    } 
}; 

updateAddress.event();