Google Maps API Multiple Markers with Infowindows
If you also want to bind closing of infowindow to some event, try something like this
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
windows.push(infowindow)
google.maps.event.addListener(map,'click', function(){
infowindow.close();
});
};
})(marker,content,infowindow));
Source Link
Demo Link
The following code will show Multiple Markers with InfoWindow. You can Uncomment code to show Info on Hover as well
var map;
var InforObj = [];
var centerCords = {
lat: -25.344,
lng: 131.036
};
var markersOnMap = [{
placeName: "Australia (Uluru)",
LatLng: [{
lat: -25.344,
lng: 131.036
}]
},
{
placeName: "Australia (Melbourne)",
LatLng: [{
lat: -37.852086,
lng: 504.985963
}]
},
{
placeName: "Australia (Canberra)",
LatLng: [{
lat: -35.299085,
lng: 509.109615
}]
},
{
placeName: "Australia (Gold Coast)",
LatLng: [{
lat: -28.013044,
lng: 513.425586
}]
},
{
placeName: "Australia (Perth)",
LatLng: [{
lat: -31.951994,
lng: 475.858081
}]
}
];
window.onload = function () {
initMap();
};
function addMarkerInfo() {
for (var i = 0; i < markersOnMap.length; i++) {
var contentString = '<div id="content"><h1>' + markersOnMap[i].placeName +
'</h1><p>Lorem ipsum dolor sit amet, vix mutat posse suscipit id, vel ea tantas omittam detraxit.</p></div>';
const marker = new google.maps.Marker({
position: markersOnMap[i].LatLng[0],
map: map
});
const infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 200
});
marker.addListener('click', function () {
closeOtherInfo();
infowindow.open(marker.get('map'), marker);
InforObj[0] = infowindow;
});
// marker.addListener('mouseover', function () {
// closeOtherInfo();
// infowindow.open(marker.get('map'), marker);
// InforObj[0] = infowindow;
// });
// marker.addListener('mouseout', function () {
// closeOtherInfo();
// infowindow.close();
// InforObj[0] = infowindow;
// });
}
}
function closeOtherInfo() {
if (InforObj.length > 0) {
InforObj[0].set("marker", null);
InforObj[0].close();
InforObj.length = 0;
}
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: centerCords
});
addMarkerInfo();
}
Here is the code snippet which will work for sure. You can visit below link for working jsFiddle and explainantion in detail. How to locate multiple addresses on google maps with perfect zoom
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'mouseover', (function(marker) {
return function() {
var content = address;
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker));
You could use a closure. Just modify your code like this:
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
Here is the DEMO