2015-10-22 195 views
2

我使用NPM包稱爲request作出HTTP請求到https://maps.googleapis.com/maps/api/geocode/json?address=Jur%C4%8Dkova+cesta+225&key=AIzaSyChkPdCaAaVZwYof8ZbKspokuYt41NlJ_0JSON.parse返回[對象]從JSON

現在我想分析我接收,以便提取該數據的LAT/LONG和把它寫入我的數據庫。但到目前爲止,我得到的是輸出到控制檯:

[ { address_components: 
    [ [Object], 
     [Object], 
     [Object], 
     [Object], 
     [Object], 
     [Object], 
     [Object] ], 
    formatted_address: 'Breznikova ulica 15, 1230 Domžale, Slovenia', 
    geometry: 
    { location: [Object], 
     location_type: 'ROOFTOP', 
     viewport: [Object] }, 
    place_id: 'ChIJR2mtdUc0ZUcRv5nXK0zEx7M', 
    types: [ 'street_address' ] }, 
    { address_components: 
    [ [Object], 
     [Object], 
     [Object], 
     [Object], 
     [Object], 
     [Object], 
     [Object] ], 
    formatted_address: 'Breznikova ulica 15, 1000 Ljubljana, Slovenia', 
    geometry: 
    { location: [Object], 
     location_type: 'ROOFTOP', 
     viewport: [Object] }, 
    place_id: 'ChIJ19Ax9OPMekcRoPvkJ6SKNEg', 
    types: [ 'street_address' ] }, 
    { address_components: 
    [ [Object], 
     [Object], 
     [Object], 
     [Object], 
     [Object], 
     [Object], 
     [Object] ], 
    formatted_address: 'Breznikova ulica 15, 2000 Maribor, Slovenia', 
    geometry: 
    { location: [Object], 
     location_type: 'ROOFTOP', 
     viewport: [Object] }, 
    place_id: 'ChIJDUicXFd2b0cRYrf99vgTPBs', 
    types: [ 'street_address' ] } ] 

這裏是我的代碼,從我的server.js文件產生這種提取物:

//get lat and long before saving from gmaps API 
//build gmaps API URL 
var urlAddress = shop.address.replace(/ /gi, '+'); 
var urlAPIKey = '&key=AIzaSyChkPdCaAaVZwYof8ZbKspokuYt41NlJ_0'; 
var url = 'https://maps.googleapis.com/maps/api/geocode/json?address='; 
url = url.concat(urlAddress).concat(urlAPIKey); 
//make a request 
request({ 
    uri: url, 
    method:"GET", 
    timeout: 100000 
    }, function(error, response, body) { 
     var gmaps = JSON.parse(body); 
     console.log(gmaps.results); 
}); 

如果有人能指出我」如果做錯了,那會很好。如果我試圖輸出對象,它只是返回undefined。

+0

什麼是輸出錯了嗎? –

+0

@torazaburo因爲當我嘗試訪問該對象時,例如gmaps.results.address_components,它只是返回undefined –

+0

@mithril_knight,檢出util.inspect,現在正確顯示對象,現在我需要找出如何調用它。謝謝你現在,你可以把它寫成答案,我會接受它 –

回答

1

它出現爲[Object]的原因是爲了便於閱讀,如果要顯示結果的完整轉儲,則必須先通過JSON.stringify傳遞它。

至於訪問address_components,結果是一個數組,所以你必須去訪問它們該陣列的特定元素(例如gmaps.results[0].address_components

+0

好吧,你應該迭代'gmaps.results',如: 'gmaps.results.forEach(function(location){ console.log(location.address_components); });' –