Does someone know how can I return the value from a function that contains getJSON The issue is I'm trying to call that function from other function in order to get the value but its all the time undefined!!!! how can I make it work??!?
function TranslateLatLanToAddress(LatLng) {
var latlng = "34.1574183,-118.437125";
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latlng + "&sensor=false";
$ = jQuery;
$.getJSON(url, function (data) {
for (var i = 0; i < data.results.length; i++) {
var address = data.results[i].formatted_address;
// var address = data.results[i].address_components[4].long_name + data.results[i].address_components[6].short_name;
//alert(address);
// alert(address);
return false;
}
});
}
function GetVal()
{
var retVal =TranslateLatLanToAddress(LatLng);
alert(retVal); //Its undefined!!!
}
AJAX calls are asynchronous. This means that while the request is being sent to the server (Google Maps) your script will continue.
This is a good thing because it means your page will continue to load while waiting for the result.
To use this to your advantage, you can use callback
methods.
function TranslateLatLanToAddress(LatLng, fnCallback) {
var latlng = "34.1574183,-118.437125";
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latlng + "&sensor=false";
$ = jQuery;
$.getJSON(url, function (data) { // getJSON is asynchronous
for (var i = 0; i < data.results.length; i++) {
var address = data.results[i].formatted_address; // get the result
fnCallback(address); // execute the callback from the parameters
}
});
}
function GetVal() {
TranslateLatLanToAddress(LatLng, function(address){ // note the new callback that takes an address as a parameter
alert(address); // the callback is fired from within the SUCCESS method and now address has a value
});
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments