2017-08-29 75 views
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" 
} 

任何想法,请,,

回答

0

我有f找到一个解决方案。恰恰是,发现我的问题。问题不在google-map-api内。这是分配了starting_points变量。