1

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;
}
Parking Master
  • 551
  • 1
  • 4
  • 20
  • 1
    Does this answer your question? [jQuery getJSON save result into variable](https://stackoverflow.com/questions/15764844/jquery-getjson-save-result-into-variable) – Snavy Nov 07 '21 at 19:11

1 Answers1

1

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;
}
Parking Master
  • 551
  • 1
  • 4
  • 20