I want to create for each marker on google maps an own window. I tried this:
// Create first marker and window
marker = new google.maps.Marker({
position: myLatlng,
map: map
});
contentString = '<div>BOX A</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
// Create second marker and window
myLatlng = new google.maps.LatLng(12.1364,-86.2514);
marker = new google.maps.Marker({
position: myLatlng,
map: map
});
contentString = '<div>BOX B</div>';
infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
and unfortunately, only the second marker has a window which contains Box B
. If I click on the first marker then the window from the second marker with Box B
pops up. I do not understand why this happens.
I noticed that each marker gets his own window if I use a new variable for the second marker and the second window like this:
// Create sceond marker and window
myLatlng = new google.maps.LatLng(12.1364,-86.2514);
marker2 = new google.maps.Marker({
position: myLatlng,
map: map
});
contentString = '<div>BOX B</div>';
infowindow2 = new google.maps.InfoWindow({
content: contentString
});
marker2.addListener('click', function() {
infowindow2.open(map, marker2);
});
But I am completely puzzled why do I need to use new variables. Why can't I overwrite the old variables?
Note: This question is about how to get multiple distinct infoWindows and is therefore different from Have just one InfoWindow open in Google Maps API v3 and Google Maps infoWindow only loading last record on markers
Here is the complete code:
<div id="map" style='height:300px'></div>
<script>
function initMap() {
// init map
var mapDiv = document.getElementById('map');
myLatlng = new google.maps.LatLng(52.4955,13.3437);
var map = new google.maps.Map(mapDiv, {
scrollwheel: false,
center: myLatlng,
zoom: 1
});
var myLatlng, marker, infowindow,contentString;
// Create first marker and window
marker = new google.maps.Marker({
position: myLatlng,
map: map
});
contentString = '<div>BOX A</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
// Create second marker and window
myLatlng = new google.maps.LatLng(12.1364,-86.2514);
marker = new google.maps.Marker({
position: myLatlng,
map: map
});
contentString = '<div>BOX B</div>';
infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
</script>