我可以使用google map api v3从A点到B点只有一个行驶距离。
代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Directions Complex</title>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body style="font-family: Arial; font-size: 13px; color: red;">
<div id="map" style="width: 400px; height: 300px;"></div>
<div id="duration">Duration: </div>
<div id="distance">Distance: </div>
<script type="text/javascript">
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), myOptions);
directionsDisplay.setMap(map);
var st=new google.maps.LatLng(51.7519, -1.2578);
var en=new google.maps.LatLng(50.8429, -0.1313);
var request = {
origin: st,
destination:en,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the distance:
document.getElementById('distance').innerHTML +=
(response.routes[0].legs[0].distance.value)/1000 + "killo meters";
alert((response.routes[0].legs[0].distance.value)/1000 + "killo meters");
// Display the duration:
document.getElementById('duration').innerHTML +=
response.routes[0].legs[0].duration.value + " seconds";
alert( response.routes[0].legs[0].duration.value + " seconds");
directionsDisplay.setDirections(response);
}
});
</script>
</body>
</html>
但我希望使用google map api v3获得多个或所有可能的行驶距离。我希望获得如下所示的多个距离。
答案 0 :(得分:1)
可以使用路线请求参数指定provideRouteAlternatives个选项,以告知DirectionsService返回多个结果。您可以按如下方式修改请求参数:
var request = {
origin: st,
destination: en,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
// Returns multiple routes
provideRouteAlternatives: true
};
您可以修改用于获取路线的事件处理程序,为每条路线创建一个新的DirectionsRenderer,如下所示(确保每次都设置正确的路线索引,否则DirectionsRenderer将在响应中渲染第一条路线) :
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Create a new DirectionsRenderer for each route
for (var i = 0; i < response.routes.length; i++) {
var dr = new google.maps.DirectionsRenderer();
dr.setDirections(response);
// Tell the DirectionsRenderer which route to display
dr.setRouteIndex(i);
dr.setMap(map);
// Code ommited to display distance and duration
}
}
}
您需要将附加距离和持续时间的代码放入此for循环中,以便为每个路径附加距离和持续时间。我在上面的代码片段中省略了这一点,但它在下面的演示文件中。
我已经创建了一个Fiddle来证明这一点。