Google 在循环中单击时地图信息窗口未打开

Google Map InfoWindow not opening on click in loop

我无法获取 Google 地图 API 上的信息 window 以在循环内点击打开,但是所有信息 windows 都显示外部点击事件。

var map;
function initMap() {
    var mapProp = {
       center: new google.maps.LatLng(-22, 133),
       zoom: 4,
       mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map'), mapProp);
}
var request = new XMLHttpRequest();
request.open('GET', 'https://...', true);
request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
        // Success!
        var data = JSON.parse(request.responseText);
        appendData(data.data);
        console.log(data, "Data received");
    } else {
        // We reached our target server, but it returned an error
    }
};
request.onerror = function() {
    // There was a connection error of some sort
};
request.send();
function appendData (data) {
    var markers = [];
    for (var i = 0; i < data.length; i++) {
        var pos = new google.maps.LatLng(data[i].Latitude, data[i].Longitude);
        markers[i] = new google.maps.Marker({
            position: pos,
            map: map,
            icon: '//...icon.png'
        });
        var infowindow = new google.maps.InfoWindow({
            content: data[i].Name
        });
        //infowindow.open(map, markers[i]); - this shows all infowindows..
        //Something wrong with this click event
        google.maps.event.addListener(markers[i], 'click', function() {
            infowindow.open(map, markers[i]);
        });
    }
};

一切顺利。为标记和 setContent 添加了描述和 id 以触发点击事件 this

markers[i] = new google.maps.Marker({
                position: pos,
                map: map,
                icon: 'icon.png',
                description:"<div style='text-transform:uppercase;'><h6 style='color:red'>" + data[i].Name + "</h6>" + data[i].Description + "</div>",
                id: i
});
google.maps.event.addListener(markers[i], 'click', function () {

                infowindow.setContent(markers[this.id].description);
                infowindow.open(map, this);
});