2011-12-12 42 views
1

我正在使用Google地图地理编码器。我有一切工作正常,但我似乎无法弄清楚如何“遍历”(解析?)JSON结果。从JSON结果中获取邮政编码值

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

我试图循环访问'address_components',为包含“postal_code”的数组测试每个“值”键。

所以这里是什么,我到目前为止已经写了一个片段:

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]` 

显然,有我丢失的东西。

仅供参考,这里是链接到谷歌地图地理编码JSON结果: http://code.google.com/apis/maps/documentation/geocoding/#JSON

感谢您的帮助! 〜阿莫斯

回答

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); 
} 
+0

唉唉...... asynchonous是我失踪了。谢谢! – amosglenn

0

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

0

首先,让我说这个感谢。刚刚帮我解决了一个问题。但是,我确实需要稍微改变代码。

我的问题是,jQuery.inArray()不返回布尔值 - 它要么在数组中返回元素的索引或-1。我弄糊涂了这一点,我不能让你的代码不改变工作if语句读取,例如:

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

当我有这一套,如果内检查true或false,代码块会在$ .each()循环的每一次迭代中运行,因为if语句总是返回-1而不是0或false。在检查$ .inArray()方法是否返回-1后,代码运行良好。再次

谢谢!