html 通过ZipCode获取城市和州

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html 通过ZipCode获取城市和州相关的知识,希望对你有一定的参考价值。

http://stackoverflow.com/questions/10340685/get-city-name-from-zip-code-google-geocoding


The HTML:

<input id="shipfrom_zip" name="shipfrom_zip" type="text"  required="" placeholder="33166">
<input type="hidden" id="shipfrom_city" name="shipfrom_city">  

<input id="shipto_zip" name="shipto_zip" type="text" required="" placeholder="33167">
<input type="hidden" id="shipto_city" name="shipto_city">


To call the function below first get the input field values where the zip codes are
stored, then pass the input field ID of the new input fields where it will be populated

address1 = document.getElementById("shipfrom_zip").value;
address2 = document.getElementById("shipto_zip").value;

// address1 = value from input field, second_parameter = the new input field ID 
codeAddress( address1, 'shipfrom_city' );
codeAddress( address2, 'shipto_city' );




<script>
// Function that accepts a zipcode and an input ID field name  
function codeAddress( zipcode, inputid ) {
    geocoder = new google.maps.Geocoder();
    // var address = document.getElementById('shipfrom_zip').value;
    geocoder.geocode({ 'address': zipcode }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {                       

            for (var component in results[0]['address_components']) {
                for (var i in results[0]['address_components'][component]['types']) {
                    if (results[0]['address_components'][component]['types'][i] == "administrative_area_level_1") {
                        // uncomment the state line to grab a state value 
                        // state = results[0]['address_components'][component]['long_name'];
                        //alert(results[0]['address_components'][1]['long_name'] + ' , '  + state);
                        console.log(results[0]['address_components'][1]['long_name'] );
					document.getElementById(inputid).value = results[0]['address_components'][1]['long_name'] ;
                    }
                }
            }                                           
        } else {
            console.log('Invalid Zipcode');
        }
    });
}    
  
</script>














以上是关于html 通过ZipCode获取城市和州的主要内容,如果未能解决你的问题,请参考以下文章

javascript 只从Google Maps API反向地理编码器获取城市和州

javascript 只从Google Maps API反向地理编码器获取城市和州

通过 Zip Google Geocode Api 查找城市和州 [关闭]

通过传递Zipcode,从Google地理编码服务中检索城市州和邮政信息

如何快速确定给定邮政编码的状态?

使用 CLGeocoder 将城市和州信息添加到 MKAnnotation