Reputation: 28545
Im currently doing this to create markers for my google map.
function createMarker(posn, title, html) {
var marker = new google.maps.Marker({ position: posn, title: title, draggable: false });
marker['infowindow'] = new google.maps.InfoWindow({ content: html });
infoWindows.push(marker['infowindow']);
google.maps.event.addListener(marker, "click", function () {
for (i = 0; i < infoWindows.length; i++) {
infoWindows[i].close();
}
this['infowindow'].open(map, this);
});
return marker;
}
im not happy with the for loop, for closing the markers, i know something similar to this can be done by using one refernce:
if (infowindow) infowindow.close();
the reason I am using code like above is because i am doing something like
markers[myPoint]['infowindow'].open(map, markers[myPoint]);
else where, (myPoint is a number).
how can i avoid this for loop to close open infowindows and do it the nice way?
Upvotes: 0
Views: 3088
Reputation: 136
Another way of doing it is only having one InfoWindow and on the marker click event you call the setContent property of the InfoWindow and then the open event with the map and the marker as parameters.
I have found this method better in my application where I have 10,000+ markers on the map.
see: http://code.google.com/apis/maps/documentation/javascript/reference.html#InfoWindow
infoWindow = new google.maps.InfoWindow();
function createMarker(posn, title, html) {
var marker = new google.maps.Marker({ position: posn, title: title, draggable: false });
marker['content'] = html;
google.maps.event.addListener(marker, "click", function () {
infoWindow.setContent(this['content']);
infoWindow.open(map, this);
});
return marker;
}
Upvotes: 3
Reputation: 152206
Just store last opened infoWindow in a global variable:
var activeInfoWindow;
function createMarker(posn, title, html) {
var marker = new google.maps.Marker({ position: posn, title: title, draggable: false });
marker['infowindow'] = new google.maps.InfoWindow({ content: html });
infoWindows.push(marker['infowindow']);
google.maps.event.addListener(marker, "click", function () {
if ( activeInfoWindow == this['infowindow'] ) {
return;
}
if ( activeInfoWindow ) {
activeInfoWindow.close();
}
this['infowindow'].open(map, this);
activeInfoWindow = this['infowindow'];
});
return marker;
}
Upvotes: 3