javascript – 从邮政编码谷歌地理编码获取城市名称

前端之家收集整理的这篇文章主要介绍了javascript – 从邮政编码谷歌地理编码获取城市名称前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在这个网站上找到了从邮政编码中获取状态的代码,但我还需要获取城市名称.

这是获取状态的代码
(注意我也使用jQuery)

var geocoder = new google.maps.Geocoder();

    $('.zip').bind('change focusout',function () {
        var $this = $(this);
        if ($this.val().length == 5) {
            geocoder.geocode({ 'address': $this.val() },function (result,status) {
                var state = "N/A";
                //start loop to get state from zip
                for (var component in result[0]['address_components']) {
                    for (var i in result[0]['address_components'][component]['types']) {
                        if (result[0]['address_components'][component]['types'][i] == "administrative_area_level_1") {
                            state = result[0]['address_components'][component]['short_name'];
                            // do stuff with the state here!
                            $this.closest('tr').find('select').val(state);
                        }
                    }
                }
            });
        }
    });

解决方法

只需添加结果[0] [‘address_components’] [1] [‘long_name’]

所以它会

var geocoder = new google.maps.Geocoder();

$('.zip').bind('change focusout',function () {
    var $this = $(this);
    if ($this.val().length == 5) {
        geocoder.geocode({ 'address': $this.val() },status) {
            var state = "N/A";
            var city = "N/A";
            //start loop to get state from zip
            for (var component in result[0]['address_components']) {
                for (var i in result[0]['address_components'][component]['types']) {
                    if (result[0]['address_components'][component]['types'][i] == "administrative_area_level_1") {
                        state = result[0]['address_components'][component]['short_name'];
                        // do stuff with the state here!
                        $this.closest('tr').find('select').val(state);
                        // get city name
                        city = result[0]['address_components'][1]['long_name'];
                        // Insert city name into some input Box
                        $this.closest('tr').find('.city').val(city);
                    }
                }
            }
        });
    }
});
原文链接:https://www.f2er.com/js/159467.html

猜你在找的JavaScript相关文章