我使用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。
什麼是輸出錯了嗎? –
@torazaburo因爲當我嘗試訪問該對象時,例如gmaps.results.address_components,它只是返回undefined –
@mithril_knight,檢出util.inspect,現在正確顯示對象,現在我需要找出如何調用它。謝謝你現在,你可以把它寫成答案,我會接受它 –