0

no código abaixo tento utilizar as váriaveis lastLatitude e lastLongitude fora do escopo local. Preciso delas em initial. Tentei muitas coisas, alguém pode me ajudar a entender?

<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>
1
  • suas variaveis estao sendo setadas de forma assíncrona, por isso quando passa na atribuicao do initial elas ainda nao foram setadas pelo callback da chamada do ajax coloca um console.log('mensagem') antes de atribuir o initial e um dentro do success pra voce ver qual executa primeito, o success vai executar depois.
    – andrepaulo
    2/03/2017 às 18:05

1 Resposta 1

1

Voce só deve executar o restante do codigo, após ter recebido a resposta assíncrona da sua chamada do ajax, ai voce pode pegar o item para dentro da function e pegar os valores diretamente.

Nao tive como testar, mas acredito que assim deva funcionar.

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

1
  • Testei e está perfeito André. Agora vou procurar entender melhor por sua explicação. Grato de mais! 2/03/2017 às 18:51

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .