0

I will like the convertToLat() function to return the variable lat from the nested function. I have tried many ways but it just can't seem to work. Any help will be appreciated. Thank you.

function convertToLat(postal_code) {
  $.getJSON("http://maps.googleapis.com/maps/api/geocode/json?address="  + postal_code, function(result){
  var lat = result.results[0].geometry.location.lat;
  return lat;
  });
return function();
}
KY Leung
  • 103
  • 1
  • 9
  • The `return lat` is without any use, because that is the return value of the `function (result)`, which goes nowhere. Instead do with `lat` what you want to do right there and then. You may call another function from that point, but don't try to access it after `convertToLat`, nor expect that function to return you the result. For more info, see referenced Q&A. – trincot Nov 08 '16 at 10:34

1 Answers1

1

Use it like below snippet

convertToLat("211011").then(function(result){
  var lat = result.results[0].geometry.location.lat;
  console.log(lat);
});

function convertToLat(postal_code){
 
 return $.getJSON("http://maps.googleapis.com/maps/api/geocode/json?address="+postal_code);
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Satendra
  • 6,755
  • 4
  • 26
  • 46