I am struggling a bit with this seemingly simple problem. I would like to add a popup message to more than one marker in Google map. The following is my current slightly simplified code:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Map1</title>
<style type="text/css">
html, body, #map-canvas {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#marker-tooltip {
display: none;
position:absolute;
width: 300px;
height: 200px;
background-color: #ccc;
margin: 15px;
}
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(52.04, -1.5),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var pinString1 = '{"lat":52.04,"lng":-1.5}';
var pinString2 = '{"lat":52.21,"lng":-1.22}';
var infowindow = new google.maps.InfoWindow({
content: "Pin1 Popup"
});
var marker = new google.maps.Marker({
position: JSON.parse(pinString1),
map: map,
title: 'Pin1 Title'
});
marker.addListener('click', function () {
infowindow.open(map, marker);
});
infowindow = new google.maps.InfoWindow({
content: "Pin2 Popup"
});
marker = new google.maps.Marker({
position: JSON.parse(pinString2),
map: map,
title: 'Pin2 Title'
});
marker.addListener('click', function () {
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
It seems that the click event is only added to the last marker. Why does this happen? How can I fix this?
PS:
Refactoring this into a function also solve the problem of using markers twice:
function CreateMarker(markerPositionString, markerTitle, infoWindowContent, map) {
var infowindow = new google.maps.InfoWindow({
content: infoWindowContent
});
var marker = new google.maps.Marker({
position: JSON.parse(markerPositionString),
map: map,
title: markerTitle
});
marker.addListener('click', function () {
infowindow.open(map, marker);
});
}