使用VueJS在谷歌地图上明确方向



我的应用程序中有以下代码:

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);创建货运路线功能。

但是,如果我在创建货物路线中的任何操作之前添加directionsDisplay.setDirections(null);,则它在第二次调用时不起作用。我认为,这可能是由于新的 DirectionsRenderer 对象,每次我调用函数时都会实例化。任何建议将不胜感激。谢谢!

在每个调用上创建新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);
}
});
},
}
}

相关内容

  • 没有找到相关文章