簡體   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