从JSON结果中获取邮政编码值
我和谷歌地图地理编码器一起工作。我的一切都很好,但我似乎不知道如何“遍历”(解析?)JSON结果 如何从地理编码器的JSON结果中获取邮政编码 我尝试循环“地址组件”,测试包含“邮政编码”的数组的每个“值”键 以下是我到目前为止所写内容的一个片段:从JSON结果中获取邮政编码值,json,google-maps,geocoding,Json,Google Maps,Geocoding,我和谷歌地图地理编码器一起工作。我的一切都很好,但我似乎不知道如何“遍历”(解析?)JSON结果 如何从地理编码器的JSON结果中获取邮政编码 我尝试循环“地址组件”,测试包含“邮政编码”的数组的每个“值”键 以下是我到目前为止所写内容的一个片段: var geocoder = new google.maps.Geocoder(); geocoder.geocode({ address : cAddress }, function(results, status) { if(status
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结果的链接,以供参考:
谢谢你的帮助!
~Amos假设
$
这里是jQuery对象,您将返回结果[0]。由于返回componentValue.long\u名称,因此请寻址\u components
集合代码>被each()
忽略。您要查找的是$.map()
,它将返回修改后的集合。还要注意,“return”不起作用。这是一个异步函数。因此,在函数运行时,父函数已经完成
$.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);
}
首先,我要感谢你。我自己刚帮我摆脱困境。然而,我不得不稍微修改一下代码
我遇到的问题是jQuery.inArray()不返回布尔值-它要么返回数组中元素的索引,要么返回-1。我对此感到困惑,如果不将if语句更改为如下内容,我就无法让您的代码正常工作:
if( $.inArray( "postal_code", typesArray ) != -1 ) {
pc = componentValue.long_name;
}
当我将其设置为检查true或false时,if块中的代码将在$.each()循环的每次迭代中运行,因为if语句总是返回-1,而不是0或false。在检查$.inArray()方法是否返回-1后,代码运行良好
再次感谢 啊。。。异步是我所缺少的。谢谢