在下面的代码中,我无法访问变量distances的值。我认为这是因为异步调用DirectionService.route。如何获得值可变距离?
var totalDistance;
var distances = new Array();
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var start = "ABC XYZ";
var end ;
var points = new Array("Location ABC", "Location PQR", "Location XYZ", "Location more", "And Some other location");
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
center: new google.maps.LatLng(13.0604220, 80.2495830),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggableCursor: "crosshair"
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
for(var j=0;j<points.length;j++)
{
end = points[j];
var waypoints = new Array();
for(var i=0; i<points.length;i++)
{
if(i!=j)
{
waypoints.push({location:points[i], stopover: true});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypoints,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var route = response.routes[0];
totalDistance = 0;
for ( var i=0;i<route.legs.length;i++)
{
totalDistance+=route.legs[i].distance.value;
}
distances.push(totalDistance);
}
});
}
/*Now I want my distances value to be accessed from here i.e outside for loop.*/
/*So that I can compare all the distances obtained */
}
google.maps.event.addDomListener(window, 'load', initialize);
编辑:我已经更新了完整的代码。 我正在尝试做的事情:我有固定的起点和一些航点(顺序不固定),我正在尝试优化航点,我的终点不是固定的,它可以是任何优化路径,但这是必要的在调用 directionService.route 方法时提供终点,因此我将其中一个航路点作为终点,仅在航路点中保留其他航路点,然后计算路线的总距离。所以每一个航路点都会一个接一个地成为终点,其他航路点仍然是航路点。我将计算所有组合的总距离,然后我将只显示距离最小的路线的方向。