2017-04-21 313 views
0

當前,我使用下面的代碼來獲取Google Places自動完成文本框,而不使用Google Maps.I需要將此地址組件提取到城市,州,郵政編碼,在place_changed事件 國家我使用這個代碼來獲取位置使用jquery提取地址到城市,州,國家,郵編

$(document).ready(function(){ 
      var places = new google.maps.places.Autocomplete(document.getElementById('MainContent_txtpostcode')); 

      google.maps.event.addListener(places, 'place_changed', function() { 
       var place = places.getPlace(); 

      }); 
     }); 

例如,如果我們的位置Shelgate路,倫敦SW11 1BD,美國Kingdom.I要提取的地址作爲路名:Shelgate路,城市:倫敦郵政編碼:SW11 1BD國家:英國。

回答

0

試試這個,這是非常簡單的:

<input type="text" id="mapLocation" /> 
<div id="data"></div> 

<script> 
$(document).ready(function() { 
    var autocomplete = new google.maps.places.Autocomplete($("#mapLocation")[0]); 
     google.maps.event.addListener(autocomplete, 'place_changed', function() { 
      var place = autocomplete.getPlace(); 

     $('#data').html('<div>Postal Code: '+place.address_components[0].long_name+'</div><div>Road Name:'+place.address_components[1].long_name+'</div><div>City:'+place.address_components[2].long_name+'</div><div>Country:'+place.address_components[2].long_name+'</div>'); 
      console.log(place.address_components); 
     }); 
}); 
</script> 

Demo of the same

+0

工作。 :) 謝謝! – Alphy

0

places.getPlace()address_components有地址字符串可再格式化爲我們選擇的集合。

請參考下面的例子:

var processAddressString = function(place) { 
    var addressString = ''; 
    place.map(function(obj) { 
     addressString += obj.long_name; 
    }); 
    return addressString; 
} 

var places = new google.maps.places.Autocomplete(document.getElementById('MainContent_txtpostcode')); 
google.maps.event.addListener(places, 'place_changed', function() { 
    var place = places.getPlace().address_components; 
    //'place' now has array of objects where each is city,state ,postcode,country etc. 
    //You now need to loop through this and extract the short_name/long_name and form the required string 
    console.log('Address is : ', processAddressString(place);) 
}); 
相關問題