NodeJs & Google Geocoder API - PullRequest
       11

NodeJs & Google Geocoder API

2 голосов
/ 22 июля 2011

Я использую NodeJ для создания веб-приложения геокодирования.Геокодирование работает хорошо, за исключением того факта, что у меня 40% ошибки 620 от Google, поэтому я теряю много адресов геокоду.

Ошибка 620: потому что http.get (....)слишком быстро выполняет запрос 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");
})

}

Ответы [ 2 ]

3 голосов
/ 21 июля 2013

Я полагаю, что проблема в том, что Google ограничивает их использование API (чтобы избежать плохой эксплуатации).
Что вы можете сделать, это создать исполнителя очереди geoRequest, который будет иметь следующие методы:

  1. Enqueue - вставка гео-запроса в хвост очереди.
  2. Dequeue - удалить гео-запрос из головы очереди.
  3. configure - я рекомендую принять объект 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
    }
    
1 голос
/ 22 июля 2011

Возможно, поэкспериментируйте с тем, сколько запросов вы можете делать в секунду, сохраняя при этом 100% успеха. Затем, всякий раз, когда вам нужно геокодировать, добавьте запрос в очередь, и у вас будет какая-то очередь, которая снимает с нее вещи и вызывает google (то есть с setInterval). Когда конкретный запрос завершен, уведомите клиента с помощью обратного вызова, прикрепленного к запросу в очереди!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...