gpt4 book ai didi

javascript - Node Js 和 Google Geocode API

转载 作者:搜寻专家 更新时间:2023-11-01 00:34:23 24 4
gpt4 key购买 nike

我正在使用 NodeJs 制作地理编码网络应用程序。地理编码工作正常,除了我有 40% 的错误 620 来自谷歌,所以我失去了很多地址来进行地理编码。

错误 620:因为 http.get(....) 发出的获取请求对于 Google 网络服务来说太快了。

我尝试使用 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");
})

}

最佳答案

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

  1. 入队 - 将地理请求插入队列的尾部。
  2. 出队 - 从队列头部移除地理请求。
  3. 配置 - 我建议接受在列表中包含一个 waitInterval 的 json 对象,该 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
    }

关于javascript - Node Js 和 Google Geocode API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6784228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com