Hello all,
I am having a problem displaying the alternative route from the result
of the directions service.
My problem is that the directions are being rendered on the map, but
it is always the first route (i.e. index 0) even though I am setting
it to different values through setShortestRoute() (see below).
I am following the documentation here
http://code.google.com/intl/sk-SK/apis/maps/documentation/javascript/services.html#DisplayingResults
which says I need three things:
1. Create a DirectionsRenderer object.
2. Call setMap() on the renderer to bind it to the passed map.
3. Call setDirections() on the renderer, passing it the
DirectionsResult as noted above. Because the renderer is an MVCObject,
it will automatically detect any changes to its properties and update
the map when its associated directions have changed.
I am not modifying the directionsDisplay.routeIndex anywhere else
besides my setShortestRoute().
Whenever I check with firebug, the value is 0, even though I have set
it to a different value in setShortestRoute().
Here is part of my code:
var directionsRendererOptions = {
suppressInfoWindows: true,
suppressMarkers: true,
draggable: true,
}
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new
google.maps.DirectionsRenderer(directionsRendererOptions);
function initialize() {
map = new google.maps.Map(document.getElementById('right-
container'), mapOptions);
directionsDisplay.setMap(map);
}
[snip]
function setShortestRoute(response) {
// determine the shortest route
var idx = 0;
var min_distance = response.routes[0].legs[0].distance.value;
for (i=1, n=response.routes.length; i<n; i++) {
if (response.routes[i].legs[0].distance.value <
min_distance) {
min_distance = response.routes[i].legs[0].distance.value;
idx = i;
}
}
// display the correct route on the map
console.log('set idx: ', idx);
directionsDisplay.setRouteIndex(idx);
}
function calcRoute() {
var request = {
origin: marker_from.position,
destination: marker_to.position,
travelMode: google.maps.TravelMode.DRIVING,
provideRouteAlternatives: true,
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
setShortestRoute(response);
directionsDisplay.setDirections(response);
}
});
}
Any help is appreciated!