Подтвердить что ты не робот

Автозаполнение для государственного города с использованием zipcode

Привет, у меня есть поле zipcode, когда пользователь вводит почтовый индекс размером 5/9, он должен автоматически заполнять поля состояния и города.

Есть ли что-то вроде этого usin javascript или JQuery???

Спасибо

4b9b3361

Ответ 1

Использование API Javascript Google Maps V3:

Вам нужно обратиться к этому:

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

Сделайте это: =

    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;
    }

Все это возвращает строку, содержащую город и состояние в этом формате, но вы можете настроить это для своих нужд.

Ответ 3

Нашел статью о 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 */

}

});  

Ответ 5

Все ответы приветствуются. Если вы не хотите больше усложнять код, вот вам решение.

Первый шаг:

загрузите последний файл почтового индекса страны Excel и найдите файл excel под корневой папкой (вы можете скачать его здесь)
https://data.gov.in/catalog/all-india-pincode-pirectory#web_catalog_tabs_block_10)

Второй шаг:

Вызов функции 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>

Эта функция Ajax будет вызывать " http://www.sample.com/postcode.php" файл

В файле postcode.php мы должны прочитать файл excel и вернуть состояние и значение города

postcode.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
?>

Thats All, Enjoy