Javascript 使用邮政编码自动填充州城市

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6021838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:55:08  来源:igfitidea点击:

auto fill for state city using zipcode

javascriptjquerygoogle-mapsjquery-plugins

提问by user695663

Hi i have a zipcode field when user enters a 5/9 digit zip it should auto populate the State and city fields.

嗨,当用户输入 5/9 位邮编时,我有一个邮政编码字段,它应该自动填充州和城市字段。

Is there any thing like this usin javascript or JQuery???

在 javascript 或 JQuery 中是否有这样的东西???

Thanks

谢谢

回答by slandau

Using the Javascript Google Maps V3 API:

使用 Javascript Google Maps V3 API:

You need to reference this:

你需要参考这个:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>

Do this:=

这样做:=

    var zip = <yourzipcode>;
    var lat;
    var lng;
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': zip }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            geocoder.geocode({'latLng': results[0].geometry.location}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    var loc = getCityState(results);
                }
            }
        });
        }
    }); 

function getCityState(results)
    {
        var a = results[0].address_components;
        var city, state;
        for(i = 0; i <  a.length; ++i)
        {
           var t = a[i].types;
           if(compIsType(t, 'administrative_area_level_1'))
              state = a[i].long_name; //store the state
           else if(compIsType(t, 'locality'))
              city = a[i].long_name; //store the city
        }
        return (city + ', ' + state)
    }

function compIsType(t, s) { 
       for(z = 0; z < t.length; ++z) 
          if(t[z] == s)
             return true;
       return false;
    }

This all returns a string containing the city and state in this format , but you can adjust this to your needs.

这一切都会以这种格式返回一个包含城市和州的字符串,但您可以根据需要进行调整。

回答by Himanshu Saini

Found an article on Css-tricks.com, functionality is implemented using Ziptastichttp://css-tricks.com/using-ziptastic/

在 Css-tricks.com 上找到了一篇文章,功能是使用Ziptastic实现的http://css-tricks.com/using-ziptastic/

$.ajax({
url: "http://zip.elevenbasetwo.com",
cache: false,
dataType: "json",
type: "GET",
data: "zip=" + el.val(),
success: function(result, success) {

$(".fancy-form div > div").slideDown(); /* Show the fields */

$("#city").val(result.city); /* Fill the data */
$("#state").val(result.state);

$(".zip-error").hide(); /* In case they failed once before */

$("#address-line-1").focus(); /* Put cursor where they need it */

},
error: function(result, success) {

$(".zip-error").show(); /* Ruh row */

}

});  

回答by Bob Bickel

RedLine has a zipcode APIthat does this for free. They have sample code here http://zipcodedistanceapi.redline13.com/Examples.

RedLine 有一个免费的邮政编码 API。他们在http://zipcodedistanceapi.redline13.com/Examples有示例代码。

回答by Abhilash

All answers are appreciated, If you are don't want to get into more of complexity of code, here is a solution for you.

感谢所有答案,如果您不想深入了解代码的复杂性,这里有一个适合您的解决方案。

First Step:

第一步

download latest country zip code Excel file and locate that excel file under root folder.(You can download it here)
https://data.gov.in/catalog/all-india-pincode-pirectory#web_catalog_tabs_block_10)

Second Step:

下载最新的国家邮政编码 Excel 文件并在根文件夹下找到该 Excel 文件。(您可以在此处下载)
https://data.gov.in/catalog/all-india-pincode-pirectory#web_catalog_tabs_block_10

第二步:

Call ajax function where is your form

调用 ajax 函数,你的表单在哪里

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type=”text/javascript”><br>
jQuery(document).ready(function(){
jQuery(‘.postcode‘).blur(function(){ //.postcode class of zipcode text field
var s = jQuery(this).val();
jQuery.ajax({
type: ‘POST',
url:“http://www.sample.com/postcode.php“, //file which read zip code excel     file
dataType: “json”, //is used for return multiple values
data: { ‘s' : s },
success: function(data){
try {
jQuery(“.state“).val(data.state); //region-class of state text field
jQuery(“.city“).val(data.dist);//city-class of city text filed
} catch (e) {
alert(e.Message);
}
},
error:function (xhr, status, err){
alert( “status=” + xhr.responseText + “, error=” + err );
}
});
});
});
</script>

This Ajax function will call “http://www.sample.com/postcode.php” file

这个 Ajax 函数会调用“ http://www.sample.com/postcode.php”文件

Under postcode.php file we have to read excel file and return state and city value

在 postcode.php 文件下,我们必须读取 excel 文件并返回州和城市值

postcode.php

邮政编码.php

<?php
extract ($_POST);
$s=$_POST[‘s'];  //get value from ajax
$filename=”zip.csv“; //zipcode csv file(must reside in same folder)
$f = fopen($filename, “r”);
while ($row = fgetcsv($f))
{
if ($row[1] == $s) //1 mean number of column of zipcode
 {
  $district=$row[3];  //3- Number of city column
  $state=$row[4]; //4-Number of state column
  break;
 }
}
fclose($f);
echo json_encode(
 array(“dist” => $district,
 “state” => $state,
 “zip” => $s)
);  //Pass those details by json
?>

That's All, Enjoy

就是这样,享受