使用VueJS在Google Map上清除路线指示

时间:2018-09-06 17:04:03

标签: javascript google-maps vue.js

我的应用中包含以下代码:

createCargoRoute: function(cargo_id) {
    var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();
    var storehouse = new google.maps.LatLng(53.243757, 50.269379);
    var cargo_orders = this.orders.filter(order => this.cargos[cargo_id]['orders_ids'].includes(order.id));
    var cargo_waypoints = cargo_orders.map(cargo_order => cargo_order['waypoint']);

    directionsDisplay.setMap(this.$refs.olkonmap.$mapObject);

    directionsService.route({
      origin: storehouse,
      destination: storehouse,
      travelMode: 'DRIVING',
      waypoints: cargo_waypoints,
      optimizeWaypoints: true
    }, function(result, status) {
      if(status == 'OK') {
        directionsDisplay.setDirections(result);
      }
    });
  },

它可以工作,但是当我第二次调用它来绘制另一条路线时,第一条路线不会从地图上删除。我读到我需要打电话给directionsDisplay.setDirections(null)来清除路线,例如,如果我添加setTimeout(function() { directionsDisplay.setDirections(null); }, 2000); createCargoRoute 函数。

但是,如果我在 createCargoRoute 中的任何操作之前添加directionsDisplay.setDirections(null);,则在第二次调用时无效。我认为,可能是由于新的DirectionsRenderer对象会在每次调用函数时实例化。任何意见,将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

在每个呼叫上创建新的DirectionsServiceDirectionsRenderer并不是一个好主意。将它们移动到mounted()并将实例保留在组件选项中(而不是将它们放置到data中)。也许有帮助:

export default {
    // will be accessible via this.$options because no reactive data is needed
    directionsService: null, 
    directionsDisplay: null,     
    mounted() {
        this.$options.directionsService = new google.maps.DirectionsService();
        this.$options.directionsDisplay = new google.maps.DirectionsRenderer();
        this.$options.directionsDisplay.setMap(this.$refs.olkonmap.$mapObject);
    },
    methods: {
        createCargoRoute: function(cargo_id) {

            // clear existing directions
            this.$options.directionsDisplay.set('directions', null);                

            var storehouse = new google.maps.LatLng(53.243757, 50.269379);
            var cargo_orders = this.orders.filter(order => this.cargos[cargo_id]['orders_ids'].includes(order.id));
            var cargo_waypoints = cargo_orders.map(cargo_order => cargo_order['waypoint']);

            this.$options.directionsService.route({
                origin: storehouse,
                destination: storehouse,
                travelMode: 'DRIVING',
                waypoints: cargo_waypoints,
                optimizeWaypoints: true
            }, (result, status) => {
                if(status == 'OK') {
                   this.$options.directionsDisplay.setDirections(result);
                }
            });
        },
    }
}