Google Geocoder Asynchronous Issue
I believe that I have having a timing issue with geocoder results. See a snippet of code below.
I am basically performing a geocode and getting the result. I then pass the result to a server side method via the jQuery AJAX call. Finally the result of the method returns a JSON object. Based on the result I may or may not perform a second geocode. This is where the problem lies.
You can see I have a variable hasResult
defaulted to false, and is toggled to true when a valid result has been determined. In all cases this works perfect, except when the need for a second geocode occurs. The geocode happens successfully and the code executes, but the final hasResult
check still returns false. How can this be?
var hasResult = false;
geocoder.geocode({ "address": address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$.ajax({
url: "URL",
type: "POST",
dataType: "json",
data: results
contentType: "application/json; charset=utf-8",
success: function (result) {
if (result.Valid) {
hasResult = false;
//Some other code, works perfect
} else {
geocoder.geocode({ "address": result.ValidRequest }, function (resultsNew, statusNew) {
if (statusNew == google.maps.GeocoderStatus.OK) {
开发者_如何学Go hasResult = false;
//Some other code, works perfect
}
});
}
});
});
}
});
}
});
if (hasResult == true) {
alert('Success');
} else {
alert('Fail');
}
Thanks
This is because you check the value of hasResult
before you get the results from the server. This happens, because the request is asynchrounous. You should use callbacks instead.
Edit:
Try this (this is only a mockup and is not tested, change it to improve readability, pass successOrFailure
as a parameter/callback etc.):
var hasResult = false;
var successOrFailure = function(hasResult){
if (hasResult == true) {
alert('Success');
} else {
alert('Fail');
}
};
geocoder.geocode({ "address": address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$.ajax({
url: "URL",
type: "POST",
dataType: "json",
data: results
contentType: "application/json; charset=utf-8",
success: function (result) {
if (result.Valid) {
hasResult = false;
successOrFailure(hasResult);
//Some other code, works perfect
} else {
geocoder.geocode({ "address": result.ValidRequest }, function (resultsNew, statusNew) {
if (statusNew == google.maps.GeocoderStatus.OK) {
hasResult = false;
successOrFailure(hasResult);
//Some other code, works perfect
}
});
}
});
});
}
});
}
});
精彩评论