Cómo saber en qué marcador se hizo clic en GoogleMaps

Estoy haciendo un pequeño proyecto HTML5 con Google Maps JavaScript API v3 usando JavaScript, CSS y HTML.

En esta pequeña aplicación, mi objetivo es agregar marcadores al mapa, y una vez que se hace clic en cada marcador, para mostrar información sobre el marcador.

Mi primer enfoque fue el siguiente:

var markersArray = [];

// Adds a marker to the map and push to the array.
function addMarker(location) {
    var marker = new google.maps.Marker({
        position: location,
        map: map,
        draggable: true,
        animation: google.maps.Animation.DROP,
        label: markersArray.length + "",
        title: markersArray.length + ""
    });
    markersArray.push(marker);
    marker.addListener('click', function() {
        clickMarkerEvent(markersArray.length - 1);
    });
}

//listener
function clickMarkerEvent(index) {
    alert(markersArray[index].getTitle());
}

Sin embargo, cuando hago clic en el marcador, solo obtengo información sobre el último marcador colocado en el mapa. El oyente está fallando.

Traté de corregir esto mediante el uso de ámbitos en JavaScript, e incluso eché un vistazo al enlace, sin embargo, ninguno de ellos funcionó.

Al final, se me ocurrió algo completamente diferente:

var markersArray = [];
var lastMarkerClicked;    

function addMarker(location) {
    var marker = new google.maps.Marker({
        position: location,
        map: map,
        draggable: true,
        animation: google.maps.Animation.DROP,
        label: markersArray.length + "",
        title: markersArray.length + ""
    });
    markersArray.push(marker);
    marker.addListener('click', function() {
        clickMarkerEvent();
    });
}

//listener
function clickMarkerEvent() {
    lastMarkerClicked = event.target || event.srcElement;
    alert(markersArray[lastMarkerClicked].title);
}

El problema con este último enfoque (aunque funciona) es el siguiente:

Estoy accediendo al elemento HTML, y no al elemento JavaScript en síMe veo obligado a usar los HTMLtitle atributo para realizar un seguimiento del índice, que solo se puede hacer si el título del marcador es el índice (no puede ser otra cosa)No puedo usar los métodos descritos aquí (https://developers.google.com/android/reference/com/google/android/gms/maps/model/Marker#public-method-summary) a menos que haga algo comomarkersArray[lastMarkerClicked.title], que hace referencia al último punto

En general, mi solución funciona, pero realmente no me gusta. ¿Hay una mejor manera de hacer esto?

El siguiente es mi código, ¡estoy abierto a sugerencias!

'use strict'

/*
	Best practices: For the best user experience, only one info window should be 
	open on the map at any one time. Multiple info windows make the map appear 
	cluttered. If you only need one info window at a time, you can create just 
	one InfoWindow object and open it at different locations or markers upon map
	events, such as user clicks. If you do need more than one info window, you 
	can display multiple InfoWindow objects at the same time.
*/
var infowindow;
var contentString;

var lastMarkerClicked;
var markersArray = [];

var map;

//	Initializes the map with a marker
function initMap() {

	var myLatLng = {
		lat: -25.363,
		lng: 131.044
	};

	map = new google.maps.Map(document.getElementById('map'), {
		zoom: 4,
		center: myLatLng
	});

	// This event listener calls addMarker() when the map is clicked.
	google.maps.event.addListener(map, 'click', function(event) {
		addMarker(event.latLng);
	});

	addMarker(myLatLng);
}

// Adds a marker to the map and push to the array.
function addMarker(location) {
	var marker = new google.maps.Marker({
		position: location,
		map: map,
		draggable: true,
		animation: google.maps.Animation.DROP,
		label: markersArray.length + "",
		title: markersArray.length + ""
	});
	markersArray.push(marker);
	marker.addListener('click', function() {
		clickMarkerEvent();
	});
}

// Sets the map on all markers in the array.
function setMapOnAll(map) {
	for (var i = 0; i < markersArray.length; i++) {
		setMapOnMarker(i, map);
	}
}

// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
	setMapOnAll(null);
}

// Shows any markers currently in the array.
function showMarkers() {
	setMapOnAll(map);
}

function setMapOnMarker(markerIndex, map) {
	markersArray[markerIndex].setMap(map);
}

function hideMarker(markerIndex) {
	setMapOnMarker(markerIndex, null);
}

function deleteMarker(markerIndex) {
	hideMarker(markerIndex);
	markersArray[markerIndex] = null;
}

/*	
	Deletes all markers in the array by removing references to them.
	Note that the above method does not delete the marker. It simply removes the 
	marker from the map. If instead you wish to delete the marker, you should remove 
	it from the map, and then set the marker itself to null.
	https://developers.google.com/maps/documentation/javascript/markers#remove
*/
function deleteMarkers() {
	clearMarkers();

	for (var i = 0; i < markersArray.length; i++) {
		markersArray[i] = null;
	}

	markersArray = [];
}

//listeners
function clickMarkerEvent() {

	lastMarkerClicked = event.target || event.srcElement;

	if (markersArray[lastMarkerClicked.title].getAnimation() !== null) {
		markersArray[lastMarkerClicked.title].setAnimation(null);
	}
	else {
		markersArray[lastMarkerClicked.title].setAnimation(google.maps.Animation.BOUNCE);
	}
	
	contentString = '<div id="content">' +
	'<div id="siteNotice">' +
	'</div>' +
	'<h1 id="firstHeading" class="firstHeading">Marker Info</h1>' +
	'<div id="bodyContent">' +
	'<b>Locatoin:</b> <p>' + markersArray[lastMarkerClicked.title].getPosition() + '</p>' + 
	'<b>Title: </b> <p>' + lastMarkerClicked.title + '</p>' + 
	'<button onclick="hideMarkerClickEvent()">Hide Marker</button>' +
	'<button onclick="deleteMarkerClickEvent()">Delete Marker</button>' +
	'</div>' +
	'</div>';
	
	if(infowindow !== null && typeof infowindow !== 'undefined')
		infowindow.close();
	
	infowindow = new google.maps.InfoWindow({
		content: contentString,
		maxWidth: 200
	});
	infowindow.open(map, markersArray[lastMarkerClicked.title]);
}

function deleteMarkerClickEvent() {
	deleteMarker(lastMarkerClicked.title);
}

function hideMarkerClickEvent() {
	hideMarker(lastMarkerClicked.title);
}
html,
body {
	height: 100%;
	margin: 0;
	padding: 0;
}

#map {
	height: 100%;
}
<!DOCTYPE html>
<html>

<head>
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
	<meta charset="utf-8">
	<title>Simple markers</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
	<div id="map"></div>
	<script type="text/javascript" src="markers.js"></script>
	<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCGj-Dsa4PtrJiyATE_upQgOkfEkjFXqoQ&callback=initMap">
	</script>
</body>

</html>