javascript - Google Maps API delay in loading variable -
javascript - Google Maps API delay in loading variable -
i trying utilize google maps api fetch city name zipcode. not strength (i'm more of php person), using sample code found, modifications suggested friend.
the problem is, after phone call function global variable city name still @ it's initialized value of null. if, however, alert value, rest of processing has right value loaded! tried putting in time delay see if google slow in returning value, makes no difference.
here's function:
var geocoder = new google.maps.geocoder(); function getgoogleaddress(zipcode) { //var gcity = "n/a"; switch using global var defined above geocoder.geocode( { 'address': zipcode}, function (result, status) { (var component in result[0]['address_components']) { (var in result[0]['address_components'][component]['types']) { if (result[0]['address_components'][component]['types'][i] == "locality") { gcity = result[0]['address_components'][component]['short_name']; break; } } } }); }
and it's called from...including alert , pause:
gcity=""; getgoogleaddress(form.zip.value); var holdcity = gcity; var date = new date(); var curdate = null; { curdate = new date(); } while(curdate-date < 2000); alert(gcity);
as said, alert returns null, rest of processing has proper city name in gcity. if leave out alert, rest of processing fails because gcity null.
any advice or suggestions appreciated. thanks.
asynchronous.
the function (result, status) {
executed when google's servers have responded. rest of getgoogleaddress
function doesn't wait that, exits, , javascript continues execution @ var holdcity = gcity
.
the reason works after alert
, then, google have responded, , gcity variable have been executed.
possible solution:
var geocoder = new google.maps.geocoder(); function getgoogleaddress(zipcode, successfunction) { //var gcity = "n/a"; switch using global var defined above geocoder.geocode( { 'address': zipcode}, function (result, status) { (var component in result[0]['address_components']) { (var in result[0]['address_components'][component]['types']) { if (result[0]['address_components'][component]['types'][i] == "locality") { var gcity = result[0]['address_components'][component]['short_name']; successfunction(gcity); break; } } } }); }
and it's called from...including alert , pause:
getgoogleaddress(form.zip.value, function (holdcity) { var date = new date(); var curdate = null; { curdate = new date(); } while(curdate-date < 2000); alert(holdcity); });
javascript google-maps
Comments
Post a Comment