我的应用程序中包含以下代码:
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);
}
});
},
它可以工作,但是当我第二次调用它来绘制另一条路线时,第一条路线不会从 map 上删除。我读到我需要调用
directionsDisplay.setDirections(null)
来清除路线,并且可以正常工作,例如,如果我添加setTimeout(function() { directionsDisplay.setDirections(null); }, 2000);
创建CargoRoute函数。但是,如果我在createCargoRoute中的任何操作之前添加
directionsDisplay.setDirections(null);
,则在第二次调用时无效。我认为,这可能是由于新的DirectionsRenderer对象会在每次调用函数时实例化。任何意见,将不胜感激。谢谢! 最佳答案
在每个调用中创建新的DirectionsService
和DirectionsRenderer
并不是一个好主意。将它们移动到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);
}
});
},
}
}