将Google地图地址查询限制为特定邮政编码

时间:2015-02-25 15:26:50

标签: javascript google-maps

如何将Google地图地址查询服务限制为特定邮政编码或城市/城镇中的街道名称。它目前正在向我提供英国的所有地址,但我想将其限制在英国伯明翰的地址(B邮政编码)。

到目前为止

代码

JS

$(document).ready(function () {
    addressLookup();
});

function addressLookup() {
      var options = {
        componentRestrictions: {
            country: 'uk'
        }
    };
    var address = document.getElementsByClassName('form-control booking address');


    for(var i=0; i< address.length; i++){
    new google.maps.places.Autocomplete(address[i], options);
    }
        //new google.maps.places.Autocomplete(address, options);
}

HTML

<input type="text" class="form-control booking address" id="pickup" placeholder="From">
<input type="text" class="form-control booking address" id="destination" placeholder="To">

Fiddle here

1 个答案:

答案 0 :(得分:1)

如果伯明翰邮政编码的定义是以B开头的,我假设你在循环的address数组中的每个值都是一个邮政编码(是吗?):

function isBirmingham(postcode) {
    return postcode.substr(0, 1) === 'B';
}

function addressLookup() {
    var options = {
        componentRestrictions: {
            country: 'uk'
        }
    };
    var address = document.getElementsByClassName('form-control booking address');

    for (var i = 0; i < address.length; i++) {
        if (isBirmingham(address[i])) {
            new google.maps.places.Autocomplete(address[i], options);
        }
    }
}

<强>更新

如何在自动填充选项中设置componentRestrictions呢?请参阅https://developers.google.com/maps/documentation/javascript/reference#AutocompleteOptions - 仅提及您可以指定国家/地区的文档。但是this article演示了如何使用邮政编码。