I am facing a challenge with setting infoWindows for markers that are created within the callback function of a directionsService using Google Maps API V3. Despite trying various approaches, I have not been successful in achieving this task...
Below is an outline of how my code is structured:
for(i=0;i<markersList.length;i++){
map = someMap
var request = myRequestObject;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
directionsService.route(request, (function (address) {
return function(response, status) {
//Utilize the directions service to perform certain tasks
//..Then create markers
var marker = new google.maps.Marker({
map: map,
title: address['title']
});
//Add the marker to a list of markers assigned to the map
//This can be useful for deleting all markers later on
map.markers.push(marker);
//Creating multiple instances of infoWindows works fine
//However, creating one shared info window for the entire map does not work from here
//If attempted, it sets the same content for all info windows, which is not desired.
}
}
)(markersList[i])
);
}
I also tried the following approach, but encountered issues:
//Define setInfo as a custom function for my map
//Then invoke it to iterate over all markers and add info windows
google.maps.Map.prototype.setInfo = function() {
for(var i=0; i < this.markers.length; i++){
infowindow.setContent(this.markers[i].getTitle());
google.maps.event.addListener(this.markers[i], 'click', function(){
infowindow.close();
infowindow.open(map,this.markers[i]);
});
}
};
I would call this function after completing the directionsService.route (as shown in the first code block), outside the main for-loop. However, it seems unable to find any markers associated with the map for some reason...
Can anyone share insights on how to correctly link infoWindows to the map markers? I aim to use a single infoWindow instance to enable closing it when another infoWindow is clicked (infoWindow.close()).
Thank you!