gpt4 book ai didi

javascript - 使用航路点时的最短路线

转载 作者:行者123 更新时间:2023-11-28 00:54:54 25 4
gpt4 key购买 nike

我可以使用完美的路径点。但我无法获得最短的方向。我尝试使用替代路线,但它不起作用。我需要这样的东西: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);
}
});

最佳答案

正如我在评论中所说,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 航段。在这种情况下,您将需要进行更多计算以添加每条航段的距离来找到总路线距离。

希望这有帮助!

关于javascript - 使用航路点时的最短路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26338733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com