In a web page I have multiple google maps generated in a loop. And I am using the google directions api to display directions on each of the maps. The problem is that this code is displaying all the directions on the last map. Have any ideas?:
var currentPosition = new google.maps.LatLng(44.462691,26.1215866);
var directionsService = new google.maps.DirectionsService();
function DisplayLocations(){
$("#mapsContainer").empty();
for(var i=0;i<locationsDisplayed;i++){
var location=locationsArray[i];
$("#mapsContainer"+i).append('<div id="ImageMap'+i+'" style="width=250px;height:200px;"></div>');
var myOptions = {
zoom: 14,
center: currentPosition,
draggable: false,
zoomControl: false,
scrollwheel: false,
disableDoubleClickZoom: false,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById('ImageMap'+i),myOptions);
var request = {
origin: currentPosition,
destination: location.position,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
RenderDirection(map,response);
}
});
}
}
function RenderDirection(map,result) {
var directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
directionsRenderer.setDirections(result);
}
Yes, your directionsService gets overwritten in the loop. What you can do, is chain the requests. So, whenever a response returns, you trigger the next request.