【问题标题】:Waypoints not rendered - Google Maps API未呈现航点 - Google Maps API
【发布时间】:2019-04-29 18:27:50
【问题描述】:

我正在尝试从 AXIOS 调用中获取航点,并使用响应将 city 馈送到 waypts 数组中。当我尝试将航点添加到路线时,地图只会显示从开始到结束的路线。控制台在请求中没有显示任何航点。如果我手动添加航点,它们会出现。当我将waypts 打印到控制台时,路由中waypoints 字段的格式正确。 initMap() 函数中的 filterselect 是 vue 组件模板中的下拉菜单,其中包含所有路由 ID。

overview.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 的控制台日志(waypts,然后是响应)

routeid83 的 AXIOS 响应

[{"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}]

【问题讨论】:

  • 你的 javascript 控制台说什么?您要添加多少个航点?实际上,您的问题是题外话,因为给定代码无法重现该问题。请阅读How to create a Minimal, Complete, and Verifiable example
  • @MrUpsidown 无法验证代码,因为我必须包含数千行代码和文件。我相信这个问题是由calculateAndDisplayRoute() 内的for 循环中的实现引起的,以及waypts 是如何被waypoints: 误解的。我将包括控制台日志
  • 请提供一个minimal reproducible example 来证明您的问题。这不需要数千行代码。
  • @geocodezip 我不能再补充了。请尽力了解并找出问题所在。
  • @geocodezip 问题是由于函数跳过了承诺而不是等待它完成。我该如何解决这个问题?

标签: javascript google-maps vue.js axios


【解决方案1】:

directionsService.route() 在 Promise 返回之前执行。因此,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);
    }
  });
});

最小。完全的。可验证。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-24
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 2012-01-06
    相关资源
    最近更新 更多