使用jquery将地址提取到城市,州,国家,邮政编码

时间:2017-04-21 06:47:33

标签: jquery google-maps

当前,我使用以下代码获取Google地方自动填充文本框而不使用Google地图。我需要将此地址组件提取到place_changed事件中的城市,州,邮政编码,国家/地区 我正在使用此代码获取位置

 $(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 Road,London SW11 1BD,United Kingdom。我想提取地址为Road Name:Shelgate Road,城市:伦敦邮政编码:SW11 1BD国家:英国。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);)
});