I'm having difficulty setting event handlers to Google Maps markers in JavaScript. Below is my code:
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 8,
center: {lat: -35, lng: 149}
});
for (var i = 0; i < basketballCourts.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(basketballCourts[i].latitude, basketballCourts[i].longitude),
map: map,
title: 'Hello World!'
});
marker.set("data-index", i);
google.maps.event.addListener(marker, 'click', function() {
console.log(marker.get("data-index"));
});
}
You'll notice that there is a click event for the markers. However, the click event is the same for all the markers. A different number should be logged for every marker click, but no matter what marker I click on, I get the same response.
I'm not sure how to fix this.
this.get("data-index")to see if you can use this to get the correct marker.