簡體   English   中英

Google Place 自動完成郵政編碼

[英]Google Place Autocomplete for Postal Code

我正在嘗試創建一個只應提供郵政編碼的自動完成文本框。 這是我遵循的文檔: https://developers.google.com/places/webservice/autocomplete#place_types

JSFiddle 工作示例在這里

如果我使用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);

文檔不是很清楚。

  • (regions)類型集合指示Places服務返回與以下類型匹配的任何結果:
    • 局部性
    • sublocality
    • 郵政編碼
    • 國家
    • administrative_area_level_1
    • administrative_area_level_2

我使用了postal_code地址組件類型。

確保您在腳本網址中包含了位置庫,如下所示:

<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

//////////來自我的工作代碼
//////////用表單輸入ID替換getByElementId

  ////  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("");
     }

我知道這有點老了但是......我想我應該分享我的知識並希望它可以幫助某人。

@geocodezip是對的,你不能特意要求谷歌只返回郵政編碼結果。 但是,您可以請求區域並告訴用戶何時將其搞砸了!

這是我使用的代碼。 它使用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 });
});

在谷歌搜索了一段時間后,我創建了一個簡單的解決方案。 它基本上在循環遍歷后返回郵政編碼

地址_組件

 function initAutocomplete() { var inputPostCode1 = document.getElementById('input_1_2_5'); var options = { types: ['geocode'] }; autoPostcode1 = new google.maps.places.Autocomplete(inputPostCode1, options); google.maps.event.addListener(autoPostcode1, 'place_changed', function() { document.getElementById('input_1_2_5').value = getPostCode(autoPostcode1.getPlace()); }) } // initAutocomplete function getPostCode(place){ for (var i = 0; i < place.address_components.length; i++) { for (var j = 0; j < place.address_components[i].types.length; j++) { if (place.address_components[i].types[j] == "postal_code") { console.log(place.address_components[i]); return place.address_components[i].long_name; } } } }

如果不使用 javascript,請將以下 http 請求與谷歌 api 放置文本搜索端點一起使用

https://maps.googleapis.com/maps/api/place/textsearch/json?query=971&fields=formatted_address&inputtype=textquery&key=[my_key]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM