使用自动完成服务获取邮政编码

时间:2019-12-21 15:20:32

标签: javascript jquery google-maps google-places-api

我想显示带有地址的邮政编码。我在这里获得地址,但找不到邮政编码来创建自定义自动地址下拉列表。

var service = new google.maps.places.AutocompleteService();
var searchStr = '';
$("#search").keyup(function() {
    var searchStr = $("#search").val();

    service.getPlacePredictions({ input: searchStr, types: ['geocode'],
                        componentRestrictions:{ country: 'us' } },
    function (predictions, status) {

        if (status == google.maps.places.PlacesServiceStatus.OK) {
            var results = document.getElementById('results');
            jQuery("#results").empty();
            for (var i = 0, prediction; prediction = predictions[i]; i++) {
                jQuery("#results").append('<li>' + prediction.terms[0].value +','+ prediction.terms[1].value + '</li>');

                    console.log(prediction);

            }
        }
    });

});

我无法从这些代码中获取邮政编码。

1 个答案:

答案 0 :(得分:0)

getPlacePredictions方法返回一个预测对象数组,每个预测对象都暴露一个placeId。来自Google的documentation

  

要检索有关该地点的信息,请在   Place Details request的placeId字段。

然后您可以从“地方详情”调用结果中返回的postal_code数组中获取address_components

希望这会有所帮助!