I have JavaScript function call to changeMapLocation function where in it I want to return the variables lat and long1. I have some problem in code to return those two variables and alert in function call.
var sample = changeMapLocation(state);
alert(sample.lat1);
alert(sample.lat2);
function changeMapLocation(state) {
var addressval=state;
var address;
var url;
var googleUrl= "http://maps.google.com/maps/api/geocode/json?";
var sensor = "&sensor=false";
if(addressval != null && addressval !="" && addressval.length!=0) {
address = "address="+encodeURIComponent(addressval);
$.ajax({
url:googleUrl+address+sensor,
type:"POST",
dataType:"json",
success:function(longlatJson) {
var jsonObj = JSON.parse(JSON.stringify(longlatJson));
var lat = jsonObj.results[0].geometry.location.lat;
var long1 = jsonObj.results[0].geometry.location.lng;
alert(lat);
alert(long1);
//var latlng = new google.maps.LatLng(lat,long1);
//alert(latlng);
},
error:function(){alert("unable to conect to google server");}
});
}
return(lat1:lat,lat2:long1);
}
You have a bigger problem in there. You are calling the asynchronous
$.ajax()method, where its callback function will be called after yourchangeMapLocation()function returns, and therefore your function will not work as you are expecting. Follow the comments in the example below:You should consider refactoring your code in such a way that the logic to handle the ajax response is in the
successcallback. Example:Note that
changeMapLocation()does not return anything anymore. It will simply change the map location on its own, when the server responds to the Ajax request.In addition note that your
latandlong1variables were enclosed in the scope of thesuccessinner function, and couldn’t be accessed from the outer function.