Путевые точки не отображаются - API Карт Google - PullRequest
0 голосов
/ 28 ноября 2018

Я пытаюсь получить путевые точки из вызова AXIOS и использовать ответ для подачи city в массив waypts.Когда я пытаюсь добавить путевые точки к маршруту, на карте будет отображаться только маршрут от начала до конца.Консоль не показывает путевые точки в запросе.Если я добавлю путевые точки вручную, они появятся.Когда я печатаю waypts на консоль, он корректно форматируется для поля waypoints в маршруте.filterselect в функции initMap() представляет собой раскрывающийся список в шаблоне компонента vue, который содержит все идентификаторы маршрута.

review.js

function calculateAndDisplayRoute(context, directionsService, directionsDisplay) {
  var origin, dest;
  var waypts = [];
  var stops;
  for (var i=0; i<context.routes.length; i++) {
    //console.log(route)
    if(context.routes[i].id == context.filter){
      origin = context.routes[i].start;
      dest = context.routes[i].dest;
      stops = Promise.resolve(getAllStops(context.routes[i].id));
      stops.then(function(value) {
        for (var i = 0; i < value.length; i++) {
          if(!(value[i].city === dest)){
          waypts.push({
                    location: value[i].city.toString(),
                    stopover: true
                  });
              }
        }
        })
      break;
    }
  }
  console.log(waypts)
  directionsService.route({
    origin: origin,
    destination: dest,
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: 'DRIVING'
  }, function(response, status) {
    if (status === 'OK') {
      console.log(response)
      directionsDisplay.setDirections(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}

async function getAllStops(routeid){
  var stops=[];
  var thisResponse =[];
  try{
    let response = await AXIOS.get('/api/route/getStops/' + routeid + '/', {}, {});
    thisResponse = response.data;
    for (var i = 0; i < thisResponse.length; i++) {
    stops.push(response.data[i]);
    }
  }catch(error){
    console.log(error.message);
  }
  return stops;
}
//...
methods: {
      initMap: function(){
        this.$nextTick(function(){
          var directionsService = new google.maps.DirectionsService;
          var directionsDisplay = new google.maps.DirectionsRenderer;
          var map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: 45.49, lng: -73.61},
            zoom: 9
          });
          directionsDisplay.setMap(map);
          var thisContext = this;
          var onChangeHandler = function() {
            calculateAndDisplayRoute(thisContext, directionsService, directionsDisplay);
          };
          document.getElementById('filterselect').addEventListener('change', onChangeHandler);
        })
      }
}

Журнал консоли (путевые символы, затем ответ) для маршрута 83 console_log

Ответ AXIOS для routeid 83

[{"locationId":84,"city":"Johannesburg","street":"28th","user":{"ratings":[4.5,4.8,4.1,2.8],"username":"elle12","password":"****","firstName":"Elle","lastName":"Woods","phoneNumber":"**********","city":"Cape Town","address":"*** Trinidad","avgRating":4.05,"numTrips":4,"role":"passenger","car":null,"status":"Active","request":null},"route":{"routeId":83,"seatsAvailable":1,"startLocation":"Cape Town","date":"2018-12-04T15:00:00.000+0000","car":{"vehicleId":81,"brand":"Tesla","model":"X","licensePlate":"123456","driver":{"ratings":[4.0],"username":"nono12","password":"****","firstName":"Noam","lastName":"Suissa","phoneNumber":"**********","city":"Montreal","address":"345 road","avgRating":4.0,"numTrips":1,"role":"driver","car":null,"status":"Active","request":null},"route":null},"status":"Scheduled","stops":null},"price":13.0},
{"locationId":85,"city":"Hoedspruit","street":"Kruger","user":{"ratings":[2.8],"username":"george12","password":"****","firstName":"George","lastName":"Lasry","phoneNumber":"**********","city":"Johannesburg","address":"*** Hamt","avgRating":2.8,"numTrips":1,"role":"passenger","car":null,"status":"Inactive","request":null},"route":{"routeId":83,"seatsAvailable":1,"startLocation":"Cape Town","date":"2018-12-04T15:00:00.000+0000","car":{"vehicleId":81,"brand":"Tesla","model":"X","licensePlate":"123456","driver":{"ratings":[4.0],"username":"nono12","password":"****","firstName":"Noam","lastName":"Suissa","phoneNumber":"**********","city":"Montreal","address":"345 road","avgRating":4.0,"numTrips":1,"role":"driver","car":null,"status":"Active","request":null},"route":null},"status":"Scheduled","stops":null},"price":11.0}]

1 Ответ

0 голосов
/ 28 ноября 2018

directionsService.route() выполняется до возвращения Обещания.Поэтому массив waypts не заполняется во времени.

Решение:

stops.then(function(value) {
  directionsService.route({
    origin: origin,
    destination: dest,
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: 'DRIVING'
  }, function(response, status) {
    if (status === 'OK') {
      console.log(response)
      directionsDisplay.setDirections(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
});

Минимально.Полная.Проверяемость.

...