Google API地理编码OVER_QUERY_LIMIT,每秒5个地址?

时间:2016-03-31 14:55:05

标签: javascript google-api geocoding

首先,我没有达到2,500个地址的最高每日限额。

我有25个地址,我已经在JavaScript中将每个地址的休眠时间设置为5秒。在18或19个地址进行地理编码后,我总是得到OVER_QUERY_LIMIT错误。其余的7或6地址始终没有进行地理编码。

Google API地理编码限制为每秒5个地址,还是增加了?

感谢。

代码

function geocodeAddress(geocoder, addresses ) {

    var arrayLength = addresses.length;

    for (var i = 0; i < arrayLength; i++) {
        var address = String(addresses[i]);
   // alert(address)
    sleep(5000) 
        geocoder.geocode({'address': address}, function (results, status) 
    {
            if (status === google.maps.GeocoderStatus.OK) {
                var result = results[0].geometry.location;
                var name = results[0].formatted_address;
                writeFile(geocode_file_path, name + ',' + result.toString());
            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }
}

function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds){
        break;
        }
}   
}

1 个答案:

答案 0 :(得分:0)

这是一个复杂的问题。 Async非常难以理解。

话虽如此,这里有一个可行的解决方案。我更喜欢基于Promise的解决方案,但Promises是另一个需要时间来理解的问题。

function geocodeAddresses(geocoder, addresses, callback){

    var result = [];

    // this internal function does the hard work
    function geocode(address) {
        // get timestamp so we can use it to throttle later
        var lastCall = Date.now();
        // call google function asynchronously
        geocoder.geocode({'address': address}, function (results, status) {
            // process the return data here
            if (status === google.maps.GeocoderStatus.OK) {
                result.push({
                    location: results[0].geometry.location,
                    address: results[0].formatted_address
                });
            } else {
                result.push({ error: status });
            }

            // check to see if there are any more addresses to geocode
            if (addresses.length) {
                // calculate when next call can be made. 200ms is 5 req / second
                var throttleTime = 200 - (lastCall - Date.now());
                setTimeout(function(){      // create timeout to run in 'throttletime` ms
                    // call this function with next address
                    geocode(addresses.shift());
                }, throttleTime);

            } else {        // all done return result
                callback(result);
            }

        });
    }

    // start the process - geocode will call itself for any remaining addresses
    geocode(addresses.shift());
}

由于此函数是异步的,因此必须异步使用它...因此回调。所以你按如下方式使用它:

geocodeAddresses(geocoder, addresses, function(result){
    // do what you need with the result here
    console.log(result);
});

这就像我能做到的一样简单。我创建了一个jsbin来模拟地理编码器调用并显示实际结果。将throttleTime更改为更大的数字,以使其变慢。

我希望这会有所帮助。