Google InfoWindow没有在循环内部加载

Google InfoWindow not loading inside for loop

本文关键字:循环 内部 加载 InfoWindow Google      更新时间:2023-09-26

我已经在我的一个网站上的谷歌地图中添加了以下代码。该地图包含许多从WordPress后台设置的坐标中提取的点。

我还想包括一些静态点,它们将永远留在地图上,并对它们的坐标进行硬编码。

下面是我正在使用的代码,结果是代码显示了第一个标记,但没有显示信息框。因此,代码将停止,并且不会继续执行for循环。问题出在return function()位,但我不确定如何使其工作。

var infowindow = new google.maps.InfoWindow({maxWidth: 185});
var setMarker;
var setMarkers = new Array();
var setLocations = [
['<h4>Location1</h4>', 53.4264,-6.2499, '/wp-content/themes/path/to/airport_icon.png'],
['<h4>Location2</h4>', 53.3461,-6.2969, '/wp-content/themes/path/to/train_icon.png'],
['<h4>Location3</h4>', 53.3532,-6.2468, '/wp-content/themes/path/to/train_icon.png'],
['<h4>Location4</h4>', 53.4264,-6.2499, '/wp-content/themes/path/to/dvc_icon.png'],
['<h4>Location5</h4>', 53.4264,-6.2499, '/wp-content/themes/path/to/dvc_icon.png'],
        ];

for (var i = 0; i < setLocations.length; i++) {  
                marker = new google.maps.Marker({
                map: map,
                position: new google.maps.LatLng(setLocations[i][1], setLocations[i][2]),
                icon : setLocations[i][3],
        });
setMarkers.push(setMarker);
google.maps.event.addListener(setMarker, 'click', (function(setMarker, i) {
                return function() {
                infowindow.setContent(setLocations[i][0]);
                infowindow.open(map, setMarker);
                }
        })(setMarker, i));
}

在for循环中定义setMarker变量,并将其推送到标记数组:

for (var i = 0; i < setLocations.length; i++) {
    var setMarker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(setLocations[i][1], setLocations[i][2])
    });
    google.maps.event.addListener(setMarker, 'click', (function (setMarker, i) {
        return function () {
            infowindow.setContent(setLocations[i][0]);
            infowindow.open(map, setMarker);
        }
    })(setMarker, i));
    setMarkers.push(setMarker);
}

JSFiddle演示