I have tried reverse Geocoding with multiple requests at a time...
My coding is below:
var latlon=new Array();
var lname="";
latlon[0]=new array("11.19","71.20");
latlon[1]=new array("12.89","72.22");
latlon[2]=new array("13.49","73.64");
for(i=0;i<3;i++)
{
lname=locationname(latlon[i][0],latlon[i][1]);
alert(lname);
}
function locationname(lat,lon)
{
var llng = new google.maps.LatLng(lat,lon);
ligeocoder.geocode({'latLng': llng}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
if (results[0])
{
loname=results[0].formatted_address;
}
else
{
alert("result failed");
}
}
else
{
alert("Geocoder failed due to: " + status);
}
});
}
It shows error: Geocoder failed due to: OVER_QUERY_LIMIT
This is a limit of the Google geocoding API, not javascript. Basically google will not let you make too many requests at a time, there is no way to get around this limit without breaking the google api terms of service.
If you want to limit the amount of calls you're doing at a time, put your geocoding function in a setInterval.
Related
google.maps.Geocoder().geocode always return REQUEST_DENIED with all the APIs enabled in a commercial google map account
We tried to use a key of a paid commercial account with all the APIs (15 of them) enabled but still got REQUEST_DENIED when calling google.maps.Geocoder().geocode
new google.maps.Geocoder().geocode( { 'address': site.address}, function(results, status) {
//console.log('address:'+ site.address)
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
site.latitude = latitude
site.longitude = longitude
if (callback) {
callback(site)
}
} else {
if (errorHandler) {
errorHandler.call(self, "Invalide address")
}
}
});
The REQUEST_DENIED error status code usually means there is an issue with your project setup or api key. Besides enabling billing, to use Google's Geocoder:
You need to use an API key.
The Geocoding API and the Javascript API must be enabled.
The API key must be properly restricted.
Hope this helps you and anyone else who encounters this error.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Google map sync geocode delay
(2 answers)
Closed 4 years ago.
I am trying to get address info for my project. I can see the address by alert() method if i write it inside the geocode function. but if i outside of the function, it returns undefined.
tried to write the variable name like window.adres but didnt work. i think because of an another function with is parent of this.
how to make that variable global and change the value?
var geocoder = new google.maps.Geocoder;
var adres;
var latlng = {lat: parseFloat(lat), lng: parseFloat(lon)};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
adres = results[0].formatted_address;
//window.adres = ... is not working. i think because of an another function which is parent of these lines.
alert(adres); //returns address
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
alert(adres); //returns undefined
also i tried that
var geocoder = new google.maps.Geocoder;
var latlng = {lat: parseFloat(lat), lng: parseFloat(lon)};
var adres = geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
return results[0].formatted_address;
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
alert(adres); //returns undefined too
If you set a global variable with window dot whatever, you will be able to get to it later by calling the same (fully qualified) variable.
Here is an example that proves this (run the snippet to see it in action).
function setVarInFunction(){
window.adres = 'here is some text';
}
console.log(window.adres); // should be undefined
setVarInFunction();
console.log(window.adres); // now there should be something
The reason alert(adres) is not working the way you expect is that:
you create a variable at the beginning
you execute an asynchronous request off to Google to do some work, and update your variable when it comes back from Google
you execute your alert to show the var value, but you have no guarantee that Google has actually responded yet with it's data (it almost certainly has not yet responded)
What do you want to do with that value? You almost certainly don't want to just alert() it, right? Whatever you want to do with it, you should do in the block where it comes back from Google with success or failure.
You are missing the ending of your anonymous function.
This is an issue related to the callbacks in javascript.
Geocoder takes time to process your request. Thus, you alert address while it is not yet defined.
I have updated your code to new coding standards and added comments :
let geocoder = new google.maps.Geocoder;
let latlng = { lat: parseFloat(lat), lng: parseFloat(lon) };
let address = null;
// 1. The geocoder starts the process to find the address
geocoder.geocode({'location': latlng}, (results, status) => {
// 3. The geocoder finally located the address, because it takes time.
if (status === 'OK') {
if (results[0]) {
// This updated the variable with the correct result.
address = results[0].formatted_address;
// You should call here a new function, in order to do the rest of your work
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
// 2. you output address
alert(address); // This won't work as address is set by the geocoder which is asynchronous
Hope this helps.
I already searched in a lot of websites for a solution but no one of them worked.
Since hours I am trying to get the name of the city by using the latitude and longitude values which I will get from a input box to my x, y variables but no example worked.
I also read in the Google maps API but it was not useful.
I already have an API key.
Do you maybe have any solution?
This example I got from the website and tried but without success:
function myFunction() { var x='xxxxx'; var y='xxxxx'; //my coordinates
var geocoder = new google.maps.Geocoder;
var latlng = {lat: parseFloat(x), lng: parseFloat(y)};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
// ...
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
Look out for Geo location API
Sample Request
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false
I am using Google's maps API to geocode two addresses. I defer the returned results and use a $.when().then() method to execute my logic once I get the coordinates for the string addresses. The problem is the API always returns the result as resolved, even if there is an error. For example if there is no internet connection instead of request timing out I get the status as ERROR and result as null or if I enter an invalid address I get the status ZERO_RESULTS and result an empty array []. As I am only interested in getting the proper coordinate results I want to handle all other responses as a geocoding error, which I don't know how to do. You can also see that I have to check if input fields are empty before geocoding because of the same problem.
I am just getting acquainted to asynchronous flow and need some guidance.
I am using jquery 1.9.2 and google maps APIv3. (I can hard code all the conditions but I want to improve my coding skills and have something more generic. Is that possible.)
I will give my code here as well.
function geocode(addString) {
var deferred = $.Deferred();
var geocoder = new google.maps.Geocoder();
var request = {
address: addString
};
geocoder.geocode(request, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
deferred.resolve(results[0].geometry.location);
}
else {
// no idea what to do here
}
});
return deferred;
}
function Options() {
var origin = $("#origin-field").val();
var destination = $("#destination-field").val();
if (origin != "" && destination != ""){
var originCoords = geocode(origin);
var destinationCoords = geocode(destination);
$.when(originCoords, destinationCoords)
.then(function(originCoordinates, destinationCoordinates) {
console.log(originCoordinates.lat() + ',' + originCoordinates.lng());
console.log(destinationCoordinates.lat() + ',' + destinationCoordinates.lng());
}, function() {
toastMessage("Geo-coding error");
});
}
else {
toastMessage("Origin and/or Destination missing");
}
}
I solved my problem thanks to this example. As I said I just started looking at asynchronous flow so didn't know how to solve this simple problem.
What I did is just catch all non-OK statuses in an else block and passed it to the deferred.reject() method. So my code became like this.
function geocode(addString) {
var deferred = $.Deferred();
var geocoder = new google.maps.Geocoder();
var request = {
address: addString
};
geocoder.geocode(request, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
deferred.resolve(results[0].geometry.location);
}
else {
deferred.reject(status);
}
});
return deferred;
}
function Options() {
var origin = $("#origin-field").val();
var destination = $("#destination-field").val();
var originCoords = geocode(origin);
var destinationCoords = geocode(destination);
$.when(originCoords, destinationCoords)
.then(function(origin, destination) {
//some logic in case of success
}, function(status) {
toastMessage("Geo-coding error:" + status);
});
}
First of all, I didn't reach the maximum daily limit of 2,500 addresses.
I have 25 addresses, and I already set the sleep time in JavaScript between each address to 5 seconds. I always get OVER_QUERY_LIMIT error after 18 or 19 addresses are geocoded. The rest 7 or 6 address always not get geocoded.
Google API Geocoding as limit of 5 addresses per second, or they have increased?
Thanks.
Code
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;
}
}
}
This is a complex problem. Async is very tricky to get your head around.
Having said that, here's a solution that would work. I would prefer a Promise based solution but Promises are another issue that takes time to understand.
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());
}
Since this function is asynchronous, you have to use it asynchronously ... hence the callback. So you use it as follows:
geocodeAddresses(geocoder, addresses, function(result){
// do what you need with the result here
console.log(result);
});
This is about as simple as I can make it. I've created a jsbin that mocks out the geocoder call and shows real results. Change the throttleTime to bigger numbers to see it slow down.
I hope this helps.