首先,我没有达到每日 2,500 个地址的最大限制。
我有 25 个地址,并且我已经在 JavaScript 中将每个地址之间的 sleep 时间设置为 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;
}
}
}
最佳答案
这是一个复杂的问题。异步很难让你理解。
话虽如此,这里有一个可行的解决方案。我更喜欢基于 Promise 的解决方案,但 Promise 是另一个需要时间理解的问题。
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 更改为更大的数字即可看到速度减慢。
我希望这会有所帮助。
关于javascript - Google API 地理编码 OVER_QUERY_LIMIT ,每秒 5 个地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36336943/