我正在使用谷歌地图创建一个自定义地图,显示从A到B的方向。我想显示从A到B的所有可能路线。在自定义地图中添加从A到B的方向时,它给了我只有一条路线。如何从起点获得给定目的地的所有可能路线
答案 0 :(得分:6)
您可以在provideRouteAlternatives
中将true
设置为DirectionsRequest
,以便从DirectionsResult
对象获取多条路线。
以下是documentation:
中所述的内容通常,对于任何给定的请求,只返回一个路由,除非请求的 provideRouteAlternatives 字段设置为true,其中可以返回多个路由。
然后,为了显示地图中的所有路线,您可以从每条路线获取overview_path
并将其存储在Polyline
数组中,然后将该数组传递给polylineOptions
属性DirectionsRenderer
对象。
以下是我所建议的code样本。
这里也是嵌入式代码
var map;
var polyOptions =[];
function initMap(){
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
document.getElementById('submit').addEventListener('click', function() {
removeLine(polyOptions);
polyOptions = [];
calculateAndDisplayRoute(directionsService,directionsDisplay);
});
}
function calculateAndDisplayRoute(directionsService,directionsDisplay) {
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
travelMode: 'DRIVING',
provideRouteAlternatives : true
}, function(response, status) {
if (status === 'OK') {
if (status === google.maps.DirectionsStatus.OK) {
var pathPoints ;
for(var i = 0; i<response.routes.length; i++){
var routeLeg = response.routes[i].legs[0];
pathPoints = response.routes[i].overview_path;
var polyPath = new google.maps.Polyline({
path: pathPoints,
strokeColor: "Blue",
strokeOpacity: 0.7,
strokeWeight: 5,
map: map
})
polyOptions.push(polyPath);
}
directionsDisplay.setDirections(response);
directionsDisplay.setOptions({
polylineOptions: polyOptions,
suppressPolylines : true
});
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
function removeLine(options) {
for(var i = 0; i < options.length; i++)
options[i].setMap(null);
}
&#13;
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
&#13;
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Multiple Routes</title>
</head>
<body>
<div id="floating-panel">
<strong>Start:</strong>
<input id="start" type="text" value="chicago">
<strong>End:</strong>
<input id="end" type="text" value="Oklahoma">
<input id="submit" type="button" value="Get Route">
<!-- <br> -->
</div>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB7fqfSyuj-jkh9cNGL63Jin5t4aHXIRUE&callback=initMap">
</script>
</body>
</html>
&#13;