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;
}
1

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.