NodeJS Google Maps API等待

时间:2017-03-30 12:35:57

标签: node.js google-maps

for(i =0; i < data.length; i++){
                console.log("i is " + i);
                 var test= data[i].payload.id;
                console.log(test);
              if(recentarray.indexOf(test)==-1){
                recentarray.push(test);
              each_device_recent_long.push(data[i].payload.long);
              each_device_recent_lat.push(data[i].payload.lat);
              each_device_recent_id.push(data[i].payload.id);
              var address;
              googleMapsClient.reverseGeocode({
                //address: '1600 Amphitheatre Parkway, Mountain View, CA'
                latlng: [ each_device_recent_lat[i], each_device_recent_long[i]]
              }, function(err, response) {
                if (!err) {
                  console.log("here are the results from google");
                  console.log(response.json.results[0].formatted_address);
                  address = response.json.results[0].formatted_address;
                  //res.render('sigfox-logs', { print_recent_array: print_recent_array});
                }
              });
                print_recent_array.push([data[i].payload.id,data[i].payload.long,data[i].payload.lat,address]);
              }
            }
            res.render('sigfox-logs', {title:'Item Locations',
                                      entries:data,
                                      sensorLong:recent_long,
                                      sensorLat: recent_lat,
                                      each_device_recent_long:  each_device_recent_long,
                                      each_device_recent_lat:   each_device_recent_lat,
                                      each_device_recent_id :each_device_recent_id,
                                    print_recent_array: print_recent_array  });

我正在尝试对谷歌地图反向地理编码服务进行API调用。这一切都运行良好,但是从谷歌获取信息需要一段时间,并且呈现给HTML的信息是“未定义的”,尽管地图名在控制台日志中显示,在页面被渲染之后

我知道它与回调有关,我调查了“请求”库,但似乎随着网站的增长,googleMapsClient对象将更容易处理。

有人可以帮我找到让res.render等待信息从谷歌API返回的方法吗? 谢谢。

2 个答案:

答案 0 :(得分:0)

对我而言,您的代码看起来并不能解释Node Js的异步非阻塞特性。

方法需要

  1. 找出您需要的所有要求
  2. 提出要求
  3. 等待他们全部返回
  4. 如果结果不包含请求信息,则需要根据请求进行协调(这可能很困难)
  5. 格式化对http响应的响应
  6. 使用承诺:googleMapsClient.reverseGeocode将极大地帮助。将其转换为promise(reverseGeocodePromise)

    var localeTupleArray = zip(each_device_recent_lat, each_device_recent_long)
    var promises = map(
        reverseGeocodePromise, 
        localeTupleArray
    )
    
    all(promises).then(function(responses) {
    
    })
    

    转换为

    • 转换为承诺
    • 地图
    • zip
    • 所有

    留作程序员的练习

答案 1 :(得分:0)

我确定这里有错误,但这是基本概念:

var data = []
var recentarray = []
var each_device_recent_long = [];
var each_device_recent_lat = [];
var each_device_recent_id = [];
var print_recent_array = [];

//map loops through array, passes all values through callback function, and returns a new array
var promises = data.map(function(item) {
  //creates a promise that takes a callback. you decide with to resolve/reject promise 
  return new Promise(function(resolve, reject) {
    var test = item.payload.id
    if (recentarray.indexOf(test) == -1) {
      recentarray.push(test);
      each_device_recent_long.push(item.payload.long);
      each_device_recent_lat.push(item.payload.lat);
      each_device_recent_id.push(item.payload.id);
      var address;
      googleMapsClient.reverseGeocode({
        //address: '1600 Amphitheatre Parkway, Mountain View, CA'
        latlng: [each_device_recent_lat[i], each_device_recent_long[i]]
      }, function(err, response) {
        if (!err) {
          console.log("here are the results from google");
          console.log(response.json.results[0].formatted_address);
          address = response.json.results[0].formatted_address;
          //res.render('sigfox-logs', { print_recent_array: print_recent_array});
          print_recent_array.push([item.payload.id, item.payload.long, item.payload.lat, address])
          resolve(address)

        } else {
          reject(err)
        }
      });

    }
  })
})

Promise.all(promises)
  .then(function(result) {
    res.render('sigfox-logs', {
      title: 'Item Locations',
      entries: result,
      sensorLong: recent_long,
      sensorLat: recent_lat,
      each_device_recent_long: each_device_recent_long,
      each_device_recent_lat: each_device_recent_lat,
      each_device_recent_id: each_device_recent_id,
      print_recent_array: print_recent_array
    });
  })
  .catch(function(err) {
    console.log(err)
    res.send({
      error: err
    })
  })