jQuery return $.getJSON value

Viewed 30

How can I save "data" into "result"?

Here's the code:

function GetCoordinates(adres) {
  var result = "";
  jQuery.getJSON('https://maps.google.com/maps/api/geocode/json?address='+adres+'&sensor=false&key=AIzaSyBxhmTCArabnNgXc6IGM7EEpgohO_mECWs',function(data) {
  result = data.results[0].geometry.location["lat"] + ',' + data.results[0].geometry.location["lng"];
  });
  return result;
}
1 Answers

You're adding value to result from an anonymous function, so when you call function(data), it is adding value to result, but in the parent function, it is returning result before it is ready.

Unfortunately, there is no way to return value from an event listener.

I still cleaned your code though:

function GetCoordinates(adres) {
  var result = "";
  $.getJSON(`https://maps.google.com/maps/api/geocode/json?address=${adres}&sensor=false&key=AIzaSyBxhmTCArabnNgXc6IGM7EEpgohO_mECWs`, (data) => { 
    result = data.results[0].geometry.location["lat"] + "," + data.results[0].geometry.location["lng"];
  });
  return result;
}
Related