I am trying to geocode around 100 postcodes from a json file by looping through the postcode, however I am restricted by the OVERY_QUERY_LIMIT error after 11 postcodes. It seems I am using the geocoder too fast per second. I have tried incorporating setTimeout in to it but can;t get it to work. How can i go about slowing down the process?
code
<head>
<meta charset="UTF-8">
<title>heatmap test</title>
<style>
html {
height: 100%
}
body {
height: 100%;
margin: 0;
padding: 0;
font-family: sans-serif;
}
#map-canvas {
height: 100%
}
</style>
</head>
<body>
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="assets/gmaps.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function (event) {
var getPostcodes = function () {
//json link
var json = "http://localhost/addresses.json/";
var request = new XMLHttpRequest();
request.open('GET', json, true);
request.onload = function () {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
//GET POSTCODES IN ARRAY
var postcodesArray = [];
for (var i = 0; i < data.length; i++) {
postcodesArray.push(data[i].from_postcode);
}
//filter all falsey values from array
var postcodes = postcodesArray.filter(Boolean);
//creating object for inserting data
var testData = {
data: []
};
//GET LAT/LONG POSITIONS
//for loop to create geocode object for each postcode
for (var n = 0; n < postcodes.length; n++) {
setTimeout(function(){
GMaps.geocode({
address: postcodes[n],
callback: function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location = results[0].geometry.location;
var latitude = parseFloat(location.lat().toFixed(8)),
longitude = parseFloat(location.lng().toFixed(8));
// pushing lat and long data to object
testData.data.push({
lat: latitude,
lng: longitude
});
} else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
console.log("error");
}
}
});
}, 500);
}
console.log(testData);
}
else {
console.log("failed");
}
};
request.onerror = function () {
// There was a connection error of some sort
};
request.send();
}
getPostcodes();
});
</script>
</body>