我认为您的代码的问题在于您DirectionsRenderer
每次调用时都定义了一个新服务calcRoute
。
从演示中查看这段代码:
function initMap() {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('right-panel'));
var control = document.getElementById('floating-panel');
control.style.display = 'block';
map.controls[google.maps.ControlPosition.TOP_CENTER].push(control);
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
document.getElementById('start').addEventListener('change', onChangeHandler);
document.getElementById('end').addEventListener('change', onChangeHandler);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
directionsService.route({
origin: start,
destination: end,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
In the initMap
function, the directionsDisplay
and directionsService
services are created. Then, they are passed to the calculateAndDisplayRoute
function:
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
The calculateAndDisplayRoute
then uses this existing instance of each service, rather than recreating the directionsDisplay
service.
In your code, you have the following line in your calcRoute
function:
directionsDisplay = new google.maps.DirectionsRenderer({
...
});
然后是后续调用setPanel
等等。因为DirectionsRenderer
每次调用时都会创建一个新实例,calcRoute
所以不会更新之前的实例。您每次都需要使用相同的实例,以便重新绘制地图上的路线(而不是覆盖在前一个实例创建的路线上)并从面板中删除以前的方向(而不是拥有新的方向)简单地附加在前一个实例插入的那些之后)。