0
我使用node.js來開發Firebase雲功能。我需要連接到谷歌地圖API來獲得兩個Latlng點之間的距離。我正在做一個HTTPS獲取請求,並收到一個JSon對象的響應。問題是收到的對象在大多數情況下爲空,狀態爲:INVALID_REQUEST。但是,在極少數情況下,它會返回所需的值。我已經在瀏覽器上嘗試了我的請求的路徑和主機,並且在那裏成功檢索了json對象。我不確切知道我的問題在哪裏。它在回調中嗎?路徑?別的東西?
我給我的代碼和它的輸出。googlemapsapi返回狀態:INVALID_REQUEST和一個空的JSon對象
我的代碼是:
function getStatusCode(options, callback) {
https.get(options, function(http_res) {
var data = "";
console.log('inside the https request');
http_res.on("data", function (chunk) {
data += chunk;
console.log("I am reading the data");
console.log(data);
// callback(http_res.statusCode, data)
});
http_res.on("end", function() {
console.log("I am in the ON_END listener");
console.log('data contains: >> ' + data + ' I am in the ONEND listener')
callback(http_res.statusCode, data)
});
});
}
,我如下調用它:
console.log('startingPoints ' + startingPoints);
console.log('lat and lng are: '+lat+" , "+lng);
var options = {
host: 'maps.googleapis.com',
path: '/maps/api/distancematrix/json?units=imperial&origins='+startingPoints+'&destinations='+lat+','+lng+'&key=MY_GOOGLEMAPSAPI_KEY',
method: get
};
getStatusCode(options, function(statusCode, data){
console.log('The status code is : '+statusCode);
console.log('and data is : '+data);
// parsing json object:
jData = JSON.parse(data);
rows = jData.rows;
console.log('the length of the rows array is >> ' + rows.length + ', the length of the techs array is >> ' + techs.length);
min = -1;
for(var i = 0; i < rows.length; i++){
console.log('the array of techs + the equivalent values of the array of row >>' + techs[i] + ' and ' + rows[i].elements[0].distance.value);
if(min < 0 || rows[i].elements[0].distance.value < rows[min].elements[0].distance.value)
min = i;
console.log('minimum distance tech in the loop; the id is >> ' + techs[min] + ", and the distance is >> " + rows[min].elements[0].distance.value);
}
console.log('the min value before return is >> ' + min);
和檢索的JSON對象是:
{
"destination_addresses" : [],
"origin_addresses" : [],
"rows" : [],
"status" : "INVALID_REQUEST"
}
任何想法,請,,