I'm trying to put an infowindow with different contents using a for() but it doesn't work. this my code:
var infowindow=[];
var myMarker=[];
var marker=[];
for (i = 0; i < dl.length; i++) {
myMarker[i]=new google.maps.LatLng(lt[i], ln[i]);
marker[i] = new google.maps.Marker({
position: myMarker[i],
map: map
});
}
for (var i = 0; i < dl.length; i++) {
google.maps.event.addListener(marker[i],'mouseover', function(){
infowindow[i] = new google.maps.InfoWindow({
content:dl[i]
});
infowindow[i].open(map,marker[i]);
});
google.maps.event.addListener(marker[i],'mouseout',function() {
infowindow[i].close();
});
google.maps.event.addListener(marker[i],'click',function() {
alert("Y ahora te abriría otra pagina... si tuviera una"+i);
});
}
Everything is cool with the first for, but when I tried to use event listeners it goes bad.
the variables: dl[]
, lt[]
, ln[]
were initialized before.
The infowindow doesn't work like that. Create a single copy of the infowindow (instead of maintaining an array) and set its contents with infowindow.setContent() during the mouseover event for each marker.
Edit: Your solution in your response will work, or here is a more concise solution:
var myMarker=[];
var marker;
var infoWindow = new google.maps.InfoWindow();
for (i = 0; i < dl.length; i++) {
myMarker[i]=new google.maps.LatLng(lt[i], ln[i]);
marker = new google.maps.Marker({
position: myMarker[i],
map: map
});
(function(msg) {marker.addListener('mouseover', function() {
infoWindow.setContent(msg);
infoWindow.open(marker.get('map'), marker);
});
})(dl[i]);
marker.addListener('mouseout', function() {
infoWindow.close();
});
}