1

Please have a look at this code. I expect it to:

  1. Execute the ajax that saves two values (latitude and longitude)
  2. use these values here = var center = new google.maps.LatLng(resplat, resplon);

The problem is that the code does not execute in this order. It "jumps over" the initial Ajax and gets back to it first when the other code is run. That makes my two values useless. Can someone explain the logic behind the order the code is being executed?

 function Initialize() {
     $.ajax({
         type: "GET",
         url: 'http://ip-api.com/json',
         dataType: "json",
         success: function (resp) {
             resplat = resp.lat;
             resplon = resp.lon;
         }
     });
     // Google has tweaked their interface somewhat - this tells the api to use that new UI
     google.maps.visualRefresh = true;
     var center = new google.maps.LatLng(resplat, resplon);

     // These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
     var mapOptions = {
         zoom: 15,
         center: center,
         mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
     };
PattaFeuFeu
  • 1,828
  • 3
  • 19
  • 24
user2915962
  • 2,691
  • 8
  • 33
  • 60

1 Answers1

1

Move the code that use resplat and resplon inside of the ajax success callback:

function Initialize() {
      $.ajax({
          type: "GET",
          url: 'http://ip-api.com/json',
          dataType: "json",
          success: function (resp) {
              var resplat = resp.lat;
              var resplon = resp.lon;

              // Google has tweaked their interface somewhat - this tells the api to use that new UI
             google.maps.visualRefresh = true;
             var center = new google.maps.LatLng(resplat, resplon);

             // These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
             var mapOptions = {
                  zoom: 15,
                 center: center,
                 mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
             };
         }
      });
}

$.ajax is an async call. You have to wait until data comes (success handler). Then you can use it.

Another way is to add a .done(foo) handler:

$.ajax({...}).done(function (...) { /* do something */ }); 
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474