我正在使用谷歌地图地理编码器。我让所有的东西都工作得很好,但是我似乎不知道如何“遍历”(parse?)JSON结果。
如何从地理编码器的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地理编码器JSON结果的链接,供参考:http://code.google.com/apis/maps/documentation/geocoding/#JSON
谢谢你的帮助!~阿莫斯
发布于 2011-12-13 03:30:15
还要注意,"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);
}发布于 2011-12-12 23:58:11
假设这里的$是jQuery对象,您将获得results[0].address_components集合,因为您的return componentValue.long_name;会被each()忽略。您正在寻找的是$.map(),它将返回修改后的集合。
发布于 2012-02-07 05:32:31
首先,让我对此表示感谢。刚刚帮我走出了困境。不过,我确实需要稍微修改一下代码。
我遇到的问题是jQuery.inArray()不返回布尔值-它要么返回数组中元素的索引,要么返回-1。我对此感到困惑,如果不将if语句改为这样,我就无法让您的代码正常工作:
if( $.inArray( "postal_code", typesArray ) != -1 ) {
pc = componentValue.long_name;
}当我将其设置为检查true或false时,该if块中的代码将在$.each()循环的每次迭代中运行,因为if语句总是返回-1而不是0或false。在检查$.inArray()方法是否返回-1之后,代码顺利运行。
再次感谢!
https://stackoverflow.com/questions/8476980
复制相似问题