I have an array of info-windows corresponding to an array of markers. Now, I have a problem, I use the below code to generate an info-window, when clicking on the marker all the markers disappear unless one, also when I click on that marker there is no info-window come out. What is the wrong with my code ? or what shall I do?
Any answer will be very appreciated.
This code is inside a for loop:
infoWindoArray[i][j] = new google.maps.InfoWindow({
content:"Lat: "+this.position.lat() + "\nLng: " + this.position.lng() + "\n"+ this.customInfo,
});
google.maps.event.addListener(AllMarkers[i][j], 'click', (function(x) {
return function() {infoWindoArray[i][j].open(map,AllMarkers[i][j]);}
})(x));
Edited: I added the whole for loop to be more clear:
for (var i = 0; i < ArrayOfAllFilesData.length-1; i++) {//to select certain file.
var myarr = ArrayOfAllFilesData[i+1];
AllMarkers[i] = new Array();
for (var j=0; j < myarr.length; j++) {
var marker_center = new google.maps.LatLng(myarr[j][0],myarr[j][1]);
AllMarkers[i][j] = new google.maps.Marker({
position: marker_center,
customInfo: "Number of encounters: "+myarr[j][2],
title:'Click to zoom',
visible:true,
});
AllMarkers[i][j].setMap(map);
};
};
}
Here's a compromise approach with one infoWindow per maker but the infowindows are not created in advance. Instead, they are created on-demand, as each marker is clicked.
This way, infoWindows that will never be seen are not created. And once created, each infoWindow will be reused if the user revisits its marker.
Outside the nested i/j loops :
var AllMarkers = [];//Not necessary unless used elsewhere
function clickMarker_closure(arr) {
return function() {
if(!this.infoWin) {
this.infoWin = new google.maps.InfoWindow({
content: [
"Lat: " + this.position.lat(),
"Lng: " + this.position.lng(),
"Number of encounters: " + arr[2]
].join("\n")
});
}
this.infoWin.open(map, this);
};
}
And the nested i/j loops :
for (var i=0; i<ArrayOfAllFilesData.length-1; i++) {//to select certain file.
var myarr = ArrayOfAllFilesData[i+1],
marker;
AllMarkers[i] = [];//necessary?
for (var j=0; j < myarr.length; j++) {
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(myarr[j][0], myarr[j][1]),
title: 'Click to zoom',
visible: true,
});
AllMarkers[i][j] = marker;//necessary?
google.maps.event.addListener(marker, 'click', clickMarker_closure(myarr[j]));
}
}
Users will be unaware that the infoWindows are created on-demand.
Edit 1