googlemapsapi返回状态:INVALID_REQUEST和一个空的JSon对象

时间:2017-08-29 07:36:58

标签: javascript json node.js firebase google-maps-api-3

我正在使用node.js来开发firebase云功能。我需要连接到谷歌地图api以获得两个Latlng点之间的距离。我正在制作https get请求并接收带有JSon对象的响应。问题是收到的对象是空的,在大多数情况下状态为: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"
}

任何想法,请

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。确切地说,发现了我的问题问题不在google-map-api中。它是与starting_points变量的分配。