我可以使用航路点perfectyl.but我不能得到最短的方向。我尝试使用路线选择,但它不起作用。我需要这样的事情:http://i58.tinypic.com/2vjbt6d.jpg
有什么办法吗?
我的代码
function codeAddress(adres) {
var address = adres;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
}
});
}
function calcRoute() {
var grid = document.getElementById('GridView1');
var start = document.getElementById('DropDownList_ilce').value + "," + document.getElementById('DropDownList_il').value;
var end = document.getElementById('GridView1').rows[grid.rows.length - 1].cells[4].innerHTML + "," + document.getElementById('GridView1').rows[grid.rows.length - 1].cells[3].innerHTML;
var waypts = [];
for (var i = 0; i < grid.rows.length - 2; i++) {
waypts.push({
location: document.getElementById('GridView1').rows[i+1].cells[4].innerHTML + "," + document.getElementById('GridView1').rows[i+1].cells[3].innerHTML,
stopover: true
});
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
答案 0 :(得分:1)
正如我在评论中所说,API似乎没有提供选项参数来默认返回最短路径。
此处的关键是使用provideRouteAlternatives: true
作为DirectionsRequest属性:
var request = {
origin: 'cerkeş,çankırı',
destination: 'diyarbakır',
travelMode: google.maps.DirectionsTravelMode.DRIVING,
provideRouteAlternatives: true
};
对于给定的起点和终点,这将返回2个单独的路线。其中一个970公里,一个1137公里。
然后你必须计算哪条路线最短。你可以这样做:
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var distance = null;
var routeIndex = 0;
// Loop through the routes to find the shortest one
for (var i=0; i<response['routes'].length; i++) {
var routeDistance = response['routes'][i].legs[0].distance.value;
if (distance === null) {
distance = routeDistance;
routeIndex = i;
}
if (routeDistance < distance) {
distance = routeDistance;
routeIndex = i;
}
}
directionsDisplay.setDirections(response);
// Set route index
directionsDisplay.setOptions({
routeIndex: routeIndex
});
}
});
请注意,当您有多条路线时,关键是设置您想要显示的路线索引。
// Set route index
directionsDisplay.setOptions({
routeIndex: routeIndex
});
此示例不使用航点。我相信如果你使用航点,你最终会有多条DirectionsLeg
腿。在这种情况下,您将需要进行更多计算以添加每个腿距以查找总路线距离。
希望这有帮助!