2011-12-12 30 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後,代碼運行良好。再次

謝謝!

相關問題