我正在使用谷歌Geocode api来循环和地理编码22个邮政编码的列表并将它们存储到数据库中。我想在地理编码完成时显示一条消息,但是由于我必须使用setTimeout来避免在11个邮政编码中遇到“OVER_QUERY_LIMIT”错误,因此我的消息显示的时间比实际进程要快得多。我怎么解决这个问题?
JS
function geocodeAddress (postcode) {
geocoder.geocode({'address': postcode}, function(results, status) {
if (status === 'OK') {
var x,
resultsLength = results.length;
for(x = 0; x < resultsLength; x++) {
lat = results[x].geometry.location.lat().toFixed(8);
lng = results[x].geometry.location.lng().toFixed(8);
//send values to php file
sendLatLng(lat, lng);
}
}
else if (status == 'OVER_QUERY_LIMIT') {
//call function again after delay when error is encountered
setTimeout(function() {
geocodeAddress(postcode);
}, 200);
}
else {
console.log('Geocode was not successful: ' + status);
}
});
};
for (n = 0; n < pstcodeLength; n++) {
geocodeAddress(postcodes[n]);
//display message after loop is complete
if (n === pstcodeLength-1) {
console.log('geocoding is complete');
}
}
答案 0 :(得分:0)
JUst跟踪完成的数字。获得最大值时,请显示消息。
var cnt = 0;
function geocodeAddress(postcode) {
geocoder.geocode({
'address': postcode
}, function(results, status) {
if (status === 'OK') {
var x,
resultsLength = results.length;
for (x = 0; x < resultsLength; x++) {
lat = results[x].geometry.location.lat().toFixed(8);
lng = results[x].geometry.location.lng().toFixed(8);
//send values to php file
sendLatLng(lat, lng);
}
cnt++;
} else if (status == 'OVER_QUERY_LIMIT') {
//call function again after delay when error is encountered
setTimeout(function() {
geocodeAddress(postcode);
}, 200);
} else {
cnt++;
console.log('Geocode was not successful: ' + status);
}
if (cnt === pstcodeLength) {
console.log('geocoding is complete');
}
});
};