这是我的代码,我试图让地图显示多条路线。我听说我需要多个对象,但实际上我不知道该怎么做。有人能帮助我吗?
<script>
var mybr = document.createElement('br');
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -24.345, lng: 134.46}
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
});
var se = [ ["Telfer, WA", "Madura, WA"],
["Newman, WA", "Zanthus, WA"],
];
for (i = 0; i < se.length; i++) {
directionsDisplay.addListener('directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
displayRoute(se[i][0], se[i][1], directionsService,
directionsDisplay);
}
}
function displayRoute(origin, destination, service, display) {
var waypo = [];
var wp = [ ["-26.170357", "126.535148"],
["-23.715558", "133.889621"],
["-20.719814", "139.486865"],
["-30.877577", "143.568913"],
];
for (i = 0; i < wp.length; i++) {
waypo.push({
location: new google.maps.LatLng(wp[i][0],wp[i][1] ),
stopover: true
});}
service.route({
origin: origin,
destination: destination,
waypoints: waypo,
travelMode: 'DRIVING',
avoidTolls: true
}, function(response, status) {
if (status === 'OK') {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
答案 0 :(得分:0)
要显示多个路由,您需要在请求对象中将provideRouteAlternatives设置为true。然后,您可以使用directionsRenderer对象显示路径。以下是一些示例代码:
directionsService.route({
origin: "Houston, TX",
destination: "Austin, TX",
travelMode: 'DRIVING',
provideRouteAlternatives: true
}, function(response, status) {
if (status === 'OK') {
for (var i = 0; i < response.routes.length; i++){
var directionsDisplay = new google.maps.DirectionsRenderer;
if(i <= 0)
directionsDisplay.setOptions({
polylineOptions: {
strokeColor: 'blue'
}
});
else
directionsDisplay.setOptions({
polylineOptions: {
strokeColor: 'red'
}
});
directionsDisplay.setRouteIndex(i);
directionsDisplay.setDirections(response);
directionsDisplay.setMap(map);
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
我在JSFiddle上演示了这个:
https://jsfiddle.net/Ly3xqqo4/1/
请注意,您需要插入自己的API密钥才能使用小提琴。
我希望这有帮助!