Web Atölyesi
Web Atölyesi

Reputation: 13

jQuery return $.getJSON value

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

Upvotes: 1

Views: 59

Answers (1)

Parking Master
Parking Master

Reputation: 626

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

Upvotes: 1

Related Questions