邮政编码的 Google 地方自动填充
Posted
技术标签:
【中文标题】邮政编码的 Google 地方自动填充【英文标题】:Google Place Autocomplete for Postal Code 【发布时间】:2015-07-02 21:25:47 【问题描述】:我正在尝试创建一个仅应提供邮政编码的自动完成文本框。这是我遵循的文档:https://developers.google.com/places/webservice/autocomplete#place_types
JSFiddle 工作示例是here
如果我使用postal_code
,它对我不起作用,但是当我使用cities
时,它很好。我应该怎么做才能实现仅使用邮政编码的自动完成功能?
function postal_code()
var input = document.getElementById('field-postal');
var options =
types: ['(postal_code)'],
componentRestrictions:
country: "in"
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addDomListener(window, 'load', postal_code);
【问题讨论】:
【参考方案1】:documentation 不是很清楚。
(regions) 类型集合指示 Places 服务返回与以下类型匹配的任何结果: 地区 次区域 邮政编码 国家 administrative_area_level_1 administrative_area_level_2
'(postal_code)'
不起作用(这是不正确的)。
'postal_code'
doesn't work either.
'(regions)'
works and includes postal_code type results
【讨论】:
你是绝对正确的我什至尝试了“区域”并且它工作但任何想法我如何才能将其专门限制为邮政编码? 如果按照我在回答中指出的方式解释文档,您将无法做到这一点。如果您将项目符号列表解释为其他“允许”类型,那么它现在应该可以工作了。【参考方案2】:我使用了postal_code地址组件类型。
确保在脚本网址中包含 places 库:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCBbt5ueucPc0u9VQDb8wFvFigV90PpTQA&libraries=places&callback=initEditClntInfoAutoComplete" async defer> </script>
工作示例
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete
//////////我的工作代码的一部分 ///////// 将 getByElementId 替换为您的表单输入 ID
//// Global Vars
var editClntInfoAutocomplete, addrStreet ="",
addressComponets =
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
;
function initEditClntInfoAutoComplete() // Callback
editClntInfoAutocomplete = new google.maps.places.Autocomplete(
/** @type !htmlInputElement */(document.getElementById('clntInfoEditAddr1')),
types: ['geocode']);
// When the user selects an address from the dropdown, populate the address
// fields in the form.
editClntInfoAutocomplete.addListener('place_changed', fillInEditClntInfoAddress);
function fillInEditClntInfoAddress()
var place = editClntInfoAutocomplete.getPlace();
clearPrevEditFrmAddrVals();
for ( var i = 0; i < place.address_components.length; i++)
var addressType = place.address_components[i].types[0];
if ( addressComponets[addressType] )
var val = place.address_components[i][addressComponets[addressType]];
assignEditFrmAddrFieldsVal(addressType, val );
if( addrStreet != "")
document.getElementById("clntInfoEditAddr1").value = addrStreet;
function assignEditFrmAddrFieldsVal( addressType , val )
switch( addressType )
case "administrative_area_level_1":
document.getElementById("clntInfoEditState").value = val; break;
case "locality":
document.getElementById("clntInfoEditCity").value = val; break;
// case "country":
// document.getElementById("addressType").value = val; break;
case "postal_code":
document.getElementById("clntInfoEditZip").value = val; break;
case "street_number":
case "route":
addrStreet += " "+val; break;
function clearPrevEditFrmAddrVals()
var editClntFrmAddrIDs = ["clntInfoEditState","clntInfoEditCity","clntInfoEditZip","clntInfoEditAddr1"];
addrStreet = "";
for( var frmID in editClntFrmAddrIDs )
wrap(editClntFrmAddrIDs[frmID]).val("");
【讨论】:
保存我的一天。types: ['geocode'] 如果您想按邮政编码 (y) 进行搜索【参考方案3】:我知道这有点老了,但是...我想我应该分享我的知识并希望它对某人有所帮助。
@geocodezip 是对的,您不能专门要求 Google 只返回邮政编码结果。但是,您可以请求区域并在用户搞砸时告诉用户!
这是我使用的代码。它使用 2 个输入;地址前缀(房屋名称/号码)和邮政编码
要求: 具有 2 个输入的 div(用于搜索)。 在其下方,一个 div 容器,其中包含具有以下 id 的输入:(这些可以作为前缀)
地址1 地址2 城市 县 邮政编码 国家我的每个用户输入都有“InputControl”类,所以我在我的函数中使用它来清除以前的值。
使用它
var autoAddr;
function initAutocomplete()
autoAddr = new google.maps.places.Autocomplete(document.getElementById('AddressSearchField'), types: ['(regions)'] );
autoAddr.addListener('place_changed', FillInAddress);
function FillInAddress()
GooglePlacesFillAddress(autoAddr, "#AddressCont", "");
主要功能
function GooglePlacesFillAddress(Place, ContainerId, AddressPrefix)
var
place = Place.getPlace(),
arr = ['premise', 'route', 'locality', 'postal_town', 'administrative_area_level_2', 'postal_code', 'country'],
dict = ,
adr = $(ContainerId).find("#" + AddressPrefix + "Address1"),
switched = false,
switchedAgain = false,
searchAgain = $("<p id=\"" + AddressPrefix + "AddressSearchAgain\"><a href=\"javascript:void(0)\" class=\"Under\">I would like to search again</a></p>"),
asc = $("#" + AddressPrefix + "AddressSearchCont"),
adressPrefixValue = $("#" + AddressPrefix + "AddressSearchPrefixField").val().trim();
SlideShow(ContainerId),
$(ContainerId).find("input.InputControl").val(''),
asc.find("#" + AddressPrefix + "AddressSearchField, #" + AddressPrefix + "AddressSearchPrefixField").attr("disabled", "disabled"),
asc.find("#" + AddressPrefix + "AddressSearchFieldButton").addClass("disabled"),
asc.find("#" + AddressPrefix + "AddressSearchPrefixField").after(searchAgain),
searchAgain.on("click", function ()
$(this).remove(),
asc.find("#" + AddressPrefix + "AddressSearchField, #" + AddressPrefix + "AddressSearchPrefixField").removeAttr("disabled").val(''),
asc.find("#" + AddressPrefix + "AddressSearchFieldButton").removeClass("disabled"),
asc.find("#" + AddressPrefix + "AddressSearchPrefixField").focus();
);
if (place.address_components && place.address_components.length)
for (var i = 0; i < place.address_components.length; i++)
for (var j = 0; j < place.address_components[i].types.length; j++)
if ($.inArray(place.address_components[i].types[j], arr) >= 0)
dict[place.address_components[i].types[j]] = place.address_components[i]["long_name"];
$(ContainerId).find("#" + AddressPrefix + "City").val(dict["postal_town"] || '');
$(ContainerId).find("#" + AddressPrefix + "County").val(dict["administrative_area_level_2"] || '');
$(ContainerId).find("#" + AddressPrefix + "Postcode").val(dict["postal_code"] || '');
$(ContainerId).find("#" + AddressPrefix + "Country").val(dict["country"] || 'United Kingdom');
var isPostal = false;
if (place.types && place.types.length)
if ($.inArray("postal_code", place.types) >= 0 && $.inArray("postal_code_prefix", place.types) < 0)
isPostal = true;
// Add street number
InputAdder(adr, adressPrefixValue, true);
// Add premise
if (adressPrefixValue.length == 0 || adr.val().length + (dict["premise"] || '').length > 100)
adr = $(ContainerId).find("#" + AddressPrefix + "Address2"), switched = true;
InputAdder(adr, (dict["premise"] || ''), true);
// Add route
if (adr.val().length + (dict["route"] || '').length > 100)
adr = $(ContainerId).find("#" + AddressPrefix + (switched ? "City" : "Address2"));
if (switched)
switchedAgain = true;
else
switched = true;
InputAdder(adr, (dict["route"] || ''), !switchedAgain, adressPrefixValue.length > 0 && adr.val() == adressPrefixValue);
// Add locality
InputAdder(switched ? adr : $(ContainerId).find("#" + AddressPrefix + "Address2"), (dict["locality"] || ''), !switchedAgain);
if (!isPostal)
WriteBorderedBox(false, ContainerId, "The postcode provided doesn't appear to be complete/valid. Please confirm the below address is correct."),
$(ContainerId).find("#" + AddressPrefix + "Address1").focus();
辅助函数
function InputAdder(Obj, Text, Post, DontAddComma)
if (Obj && Text.length > 0)
var
i = Obj.val().trim() || '',
comma = !!DontAddComma ? "" : ",";
Obj.val(
(Post && i.length > 0 ? i + comma + ' ' : '') +
Text.trim() +
(!Post && i.length > 0 ? comma + ' ' + i : ''));
function WriteBorderedBox(outcome, identifier, text)
var
box = $("<div class=\"Bordered" + (outcome ? "Success" : "Error") + "\"><p>" + text + "</p></div>");
$(identifier).before(box);
box.hide().slideDown(function () $(this).delay(6000).slideUp(function () $(this).remove(); ); );
如果你想要一个按钮(像我一样)
$("#AddressSearchFieldButton").click(function (e)
var input = document.getElementById("AddressSearchField");
google.maps.event.trigger(input, 'focus')
google.maps.event.trigger(input, 'keydown', keyCode: 40 );
google.maps.event.trigger(input, 'keydown', keyCode: 13 );
);
【讨论】:
以上是关于邮政编码的 Google 地方自动填充的主要内容,如果未能解决你的问题,请参考以下文章
在 Meteor 中使用 Google 地方信息自动填充功能