$("#btnsub").click(function () {
var add = $("#txtname").val();
var obj;
var geo = new google.maps.Geocoder;
geo.geocode({ 'address': add }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
obj = results[0].geometry.location;
obj = convert(obj);
alert(obj);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
alert(obj);
// why this alert run first instead of the upper alert()
});
$(#btnsub).click(function () { var add = $(#txtname).val(); var obj; var geo = new google.maps.Geocoder;
Share
If
geo.geocode()is an AJAX request, then the code that comes after it does not wait for the response to return before it executes.As such, the code runs out of order. The second
alert()fires, because there’s nothing to prevent it from firing. The first one fires when the AJAX response is received.If you have some other code that relies on the response, then place that code in a function, and call it from inside the callback for
geo.geocode().