从JSON结果中获取postal_code值

时间:2011-12-12 15:52:56

标签: json google-maps geocoding

我正在使用Google Maps Geocoder。我的一切工作正常,但我似乎无法弄清楚如何'遍历'(解析?)JSON结果。

如何从Geocoder的JSON结果中获取邮政编码?

我尝试循环遍历'address_components',测试包含“postal_code”的数组的每个“values”键。

所以这是我到目前为止写的一段摘录:

var geocoder = new google.maps.Geocoder();
geocoder.geocode({ address : cAddress }, function(results, status) {
    if(status == google.maps.GeocoderStatus.OK) {
        if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
            var fAddress = results[0].formatted_address;
        var contactLatLng = results[0].geometry.location;

        var postalCode = $.each(results[0].address_components, 
                function(componentIndex, componentValue) {
                    var typesArray = componentValue.types;
            if ($.inArray("postal_code", typesArray)) {
                return componentValue.long_name;
                    }
            })
        }
    }
});

具体问题是postalCode

[object Object],[object Object],[object Object],[object Object],  
[object Object],[object Object],[object Object]`

显然,我有些遗漏。

供参考,以下是Google Maps Geocoder JSON结果的链接: http://code.google.com/apis/maps/documentation/geocoding/#JSON

感谢您的帮助! 〜摩

3 个答案:

答案 0 :(得分:0)

假设$这里是jQuery对象,您将收回results[0].address_components集合,因为return componentValue.long_name;each()忽略。你要找的是$.map(),它将返回修改后的集合。

答案 1 :(得分:0)

另请注意,“返回”不起作用。这是一个异步功能。因此,当您的函数运行时,父函数已完成。

$.each(results[0].address_components, function(componentIndex, componentValue) {
     if ($.inArray("postal_code", componentValue.types)) {
           doSomeThingWithPostcode(componentValue.long_name);
     }
});

因此,您的函数必须使用结果明确地执行某些操作。例如......

function doSomeThingWithPostcode(postcode) {
     $('#input').attr('value',postcode);
}

答案 2 :(得分:0)

首先,我要感谢你。我自己帮我脱了果酱。但是,我确实需要改变代码。

我遇到的问题是jQuery.inArray()没有返回布尔值 - 它返回数组中元素的索引或-1。我对此感到困惑,我无法在不改变if语句的情况下使代码工作:

if( $.inArray( "postal_code", typesArray ) != -1 ) {
    pc =  componentValue.long_name;
}

当我设置为检查true或false时,if块中的代码将在$ .each()循环的每次迭代中运行,因为if语句总是返回-1而不是0或false 。在检查$ .inArray()方法是否返回-1之后,代码运行起来。

再次感谢!