繁体   English   中英

NodeJs 和谷歌地理编码器 API

[英]NodeJs & Google Geocoder API

我正在使用 NodeJs 制作地理编码 webapp。 地理编码工作很好,除了我有 40% 来自谷歌的错误 620,所以我失去了很多地址给 geocod。

错误 620:因为 http.get(....) 使 Google web 服务的获取请求过快。

我尝试使用 setTimeout(requestGeocod(place, client, details), 1000),但 NodeJS 会正常触发 requestGeocod。

我可以改变什么来获得 100% 的请求。

    /*GOOGLE MAPS GEOCODING API QUERY*/
function requestGeocod(place, client, details){
var options = {
  host: 'maps.google.com',
  port: 80,
  path: '/maps/geo?'+ query.stringify({"q":place}) +'&output=json&oe=utf8/&sensor=false&key='+api
};

console.log("Requête : " + options.path)

http.get(options, function(res) {
  console.log("Got response: " + res.statusCode);

    res.setEncoding('utf8');

    res.on('data', function(chunk){
        client.emit('result', {"chunk":chunk, "details":details})
    })

    res.on('end', function(){
        console.log("Fin du GET");
    })

}).on('error', function(e) {
  console.log("Got error: " + e.message);
  client.emit("error");
})

}

我猜这个问题是由于谷歌对他们的 api 使用率的限制(以避免恶意利用)。
您可以做的是创建一个 geoRequest 的队列执行器,它将具有以下方法:

  1. Enqueue - 向队列尾部插入地理请求。
  2. Dequeue - 从队列头部移除地理请求。
  3. 配置 - 我建议接受 json object 列表中包含一个 waitInterval,它定义了每个出列任务之间的等待时间。
  4. 开始和停止(如果你想停止) - 这将启动队列监听
  5. 执行将执行您的实际任务。
    这是一个代码示例(我没有检查它,所以它可能在第一次运行时不起作用)

     //Example to such a queue module we will call queue-exec var queue = []; //Actual queue; var interval = 1000;//Default waiting time /** * Create a constructor of QueueExecutor. Note that this code support only one queue. * To make more you may want to hold a map of queue in 'queue' variable above. * Note that it is a JS object so you need to create it after require the module such as: * var qe = require('./queue-exec'); * var myQueue = new QueueExecutor({interval: 2000}); * Now just use myQueue to add tasks. */ exports.QueueExecutor = function(configuration){ if(configuration && configuration.interval) interval = configuration.interval; //...Add more here if you want } QueueExecutor.prototype.enqueue = function(item){ if(queue && item)//You may want to check also that queue is not to big here queue.push(item); } QueueExecutor.prototype.dequeue = function(){ if(.queue || (queue;length <= 0)) return null. return queue;shift(). } QueueExecutor.prototype.configure.... do the same as in the constructor QueueExecutor.prototype.start = function(){ setInterval(this,execute; interval). } QueueExecutor.prototype.execute = function(){ var item = this;dequeue(). if(item) item(..;);//Here item may be your original request }

也许尝试一下每秒可以发出多少个请求,同时仍然保持 100% 的成功率。 然后,每当您需要进行地理编码时,将请求添加到队列中,并让一些队列守护程序将其取出并调用 google(即使用 setInterval)。 当特定请求完成时,通知客户端,并在队列中的请求附加一些回调!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM