0

I am trying to return a value from an ajax call. I have the following, which is declared in $(document).ready:

var currentUserZip = $("#user").data('zip');
var latLon = [];

I need to take the user's zip code and return coordinates from the google api. I do that using a jquery $.get call below.

function getLatLon(geoCodeQuery, latLon) {

  $.get(geoCodeQuery, function(data) {

    if (data.results.length > 0) {
      latLon.push(data.results[0].geometry.location.lat);
      latLon.push(data.results[0].geometry.location.lng);

    }

  });

}

I call the function and it will fill an array with coordinates based on a user's zip code.

getLatLon(geoCodeQuery, latLon);

However, if I check the value of latLon after the function is called, it returns an empty set.

ie. latLon = []

I would expect the coordinates to exist. Why are the coordinates not retuning? Since this is all done in the $(document).ready portion of the script, shouldn't the value carry through?

Thanks

DMiller
  • 253
  • 1
  • 3
  • 15
  • 2
    This is yet another duplicate of the everyday async question. You can't do that. `$.get` is an asynchronous operation; the items get added **after** you log the array. – elclanrs Jun 04 '14 at 23:36
  • elclanrs, what do you mean after I log the array? I am not asking this to return anything. Since I am passing latLon into the function I am expecting the array to be filled after the function "getLatLon" is run. I'm not sure what the problem is. – DMiller Jun 04 '14 at 23:44
  • Vld, latLon should get populated when getLatLon is executed. Its being executed in $(document).ready, where latLon is also declared. – DMiller Jun 04 '14 at 23:46
  • 1
    Whether you are adding the values to the `latLon` array, or trying to return it from the function doesn't matter. It's the same problem: Ajax is asynchronous. Maybe this question will make it clearer: https://stackoverflow.com/questions/23667086/why-is-my-variable-undefined-after-i-modify-it-inside-of-a-function-asynchron . Put simply: After `getLatLon` is called is still before the `$.get` callback is called. – Felix Kling Jun 04 '14 at 23:59
  • Thanks. I think I see what you guys are trying to say. – DMiller Jun 05 '14 at 00:33

0 Answers0