Doubt Scope of Javascript Variables

Asked

Viewed 177 times

0

in the code below I try to use the variables lastLatitude and lastLongitude outside the local scope. I need them in initial. I’ve tried many things, someone can help me understand?

<script>
        var lastLongitude = "";
        var lastLongitude = "";

        function initMap() {
            $.ajax({
                type: "GET",
                dataType: "JSON",
                url: "locations.json",
                success: function processJSON(data) {
                    last = $(data).last();
                    last.each(function(i, item) {
                        lastLatitude = item.latitude;
                        lastLongitude = item.longitude;
                    });
                }
            });
            var initial = {
                lat: -22.9721291, // PRECISO DELAS AQUI
                lng: -43.7081429  // PRECISO DELAS AQUI
            };

            var finish = {
                lat: -22.986,
                lng: -43.6931
            };

            var map = new google.maps.Map(document.getElementById('map'), {
                center: initial,
                scrollwheel: false,
                zoom: 7
            });

            var directionsDisplay = new google.maps.DirectionsRenderer({
                map: map
            });



            // Set destination, origin and travel mode.
            var request = {
                origin: initial,
                destination: finish,
                travelMode: 'DRIVING'
            };

            // Pass the directions request to the directions service.
            var directionsService = new google.maps.DirectionsService();
            directionsService.route(request, function(response, status) {
                if (status == 'OK') {
                    // Display the route on the map.
                    directionsDisplay.setDirections(response);
                }
            });
        }
    </script>
  • their variables are being set asynchronously, so when you pass the assignment of initial they have not yet been set by the callback of the ajax puts a console.log('mensagem') before assigning the initial and one inside the Success to Voce to see which one runs first, Success will run after.

1 answer

1


You must only execute the rest of the code, after receiving the asynchronous response from your ajax call, ai Voce can take the item into the Function and take the values directly.

I couldn’t test it, but I believe it should work.

<script>
var lastLongitude = "";
var lastLongitude = "";

function initMap() {
    $.ajax({
        type: "GET",
        dataType: "JSON",
        url: "locations.json",
        success: function processJSON(data) {
            last = $(data).last();
            last.each(function(i, item) {
              resumeTasks(item)
            });
        }
    });
    
    function resumeTasks(item) {
      var initial = {
          lat: item.latitude, // PRECISO DELAS AQUI
          lng: item.longitude  // PRECISO DELAS AQUI
      };

      var finish = {
          lat: -22.986,
          lng: -43.6931
      };

      var map = new google.maps.Map(document.getElementById('map'), {
          center: initial,
          scrollwheel: false,
          zoom: 7
      });

      var directionsDisplay = new google.maps.DirectionsRenderer({
          map: map
      });

      // Set destination, origin and travel mode.
      var request = {
          origin: initial,
          destination: finish,
          travelMode: 'DRIVING'
      };

      // Pass the directions request to the directions service.
      var directionsService = new google.maps.DirectionsService();
      directionsService.route(request, function(response, status) {
          if (status == 'OK') {
              // Display the route on the map.
              directionsDisplay.setDirections(response);
          }
      });
    
    }
    
}
</script>

  • I tested it and it is perfect André. Now I will try to understand better for your explanation. Thanks more!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.