I want to add info windows on multiple markers, placed in clusters on google maps. Here is my code below. When I tap on a marker, can not see anything. Have a look please.
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 10,
center: { lat: 62.601, lng: 29.7636 },
});
var infowindow = new google.maps.InfoWindow();
var markers = locations.map(function (location, i) {
return new google.maps.Marker({
position: location,
title: "test",
});
google.maps.event.addListener(markers, "click", function () {
infowindow.setContent("<h3>" + "testing" + "</h3>");
infowindow.open(map, this);
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers, {
imagePath:
"https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m",
});
}
In your .map()
you are returning your marker before adding the EventListener
to it, so it will never be added.
Assuming this is the correct way to add an EventListener
to a marker, do the following - Temp save it and return it after you added the EventListener
like in this snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 10,
center: { lat: 62.601, lng: 29.7636 },
});
var markers = locations.map(function (location, i) {
const marker = new google.maps.Marker({ // temp save
position: location,
title: "test",
});
google.maps.event.addListener(marker, "click", function () { // add eventlistener to marker
var infowindow = new google.maps.InfoWindow(); // probably also move infoWindow initialization in here
infowindow.setContent("<h3>" + "testing" + "</h3>");
infowindow.open(map, this);
});
return marker; // return after
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers, {
imagePath:
"https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m",
});
}