I am trying to parse an json with 400 addresses and set map icons on each location. My problem is, that when I am looping over the items I get an error: OVER_QUERY_LIMIT. But what is the best way to set the position with the google geocode api? My function looks like this:
function getAddresses(data) {
var items, markers_data = [];
if (data.addresses.length > 0) {
items = data.addresses;
for (var i = 0; i < items.length; i++) {
var
item = items[i]
, street = item.address.street
, zip = item.address.zip
, city = item.address.city
, country = item.address.country;
var
geocoder = new google.maps.Geocoder()
, fulladdress = street + ',' + zip + ' '+ city + ',' + country;
setTimeout(function () {
geocoder.geocode({'address': fulladdress},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].geometry.location.lat());
console.log(results[0].geometry.location.lng());
markers_data.push({
lat : results[0].geometry.location.lat(),
lng : results[0].geometry.location.lng(),
title: item.name,
infoWindow: {
content: '<h2>'+item.name+'</h2><p>'+ street + zip + city +'</p>'
}
});
} else {
console.log('not geocoded');
console.log('status');
console.log(status);
}
});
}, 1000);
}
}
map.addMarkers(markers_data);
}
I tried to put my geocoder.geocode function in a timeout function but unfortunately this won´t help. I am using the plugin gmaps.js in my js.
There is a per session quota for geocoder service as stated in the documentation:
The rate limit is applied per user session, regardless of how many users share the same project. When you first load the API, you are allocated an initial quota of requests. Once you use this quota, the API enforces rate limits on additional requests on a per-second basis. If too many requests are made within a certain time period, the API returns an OVER_QUERY_LIMIT response code.
The per-session rate limit prevents the use of client-side services for batch requests, such as batch geocoding. For batch requests, use the Google Maps Geocoding API web service.
https://developers.google.com/maps/documentation/javascript/geocoding#UsageLimits
So, you should throttle your client side calls and execute 1 request per second after initial 10 requests or implement a server side batch geocoding with Geocoding API web service where you can have up to 50 requests per second.
By the way in your code you try execute all requests after 1 second. You should increase a delay for each next request.
setTimeout(function () {
//Your code
}, 1000 * i);
So the first request will be executed immediately, the second after 1 sec, the third after 2 seconds and so on.
来源:https://stackoverflow.com/questions/43840766/address-geocode-via-jquery-geocoder-geocode-400-items