[英]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 的隊列執行器,它將具有以下方法:
執行將執行您的實際任務。
這是一個代碼示例(我沒有檢查它,所以它可能在第一次運行時不起作用)
//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.