1

代码非常简单,如下所示:

var populateGoogleMap = function (points) {
    for (i = points.length - 1; i >= 0; i--) {
        var marker = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: new google.maps.LatLng(point.target.x, point.target.y)
        });
        google.maps.event.addListener(marker, 'click', function (e) {
            toggleBounce(marker);
        });
        nodes[i].marker = marker;
    }
};

事实证明,markerintoggleBounce(marker)总是最后marker一个被创建的。我考虑了一下这个问题,通过修改函数找到了解决方案。我删除了函数中的循环,并在其他地方使用循环多次调用该函数。所以基本上现在它变成了for (i = 0; i < points.length; i++) { populateGoogleMap(point); }.

这种行为是 Google Maps API 的意图吗?我认为这可能会让很多人感到困惑,因为变量应该引用当前上下文中的变量。

4

1 回答 1

2

这不是谷歌地图独有的东西。您已经创建了 X 次事件侦听器函数:

google.maps.event.addListener(marker, 'click', function (e) {
    toggleBounce(marker);
});

完成循环后, 的值marker是循环中创建的最后一个值。您真正所做的只是重新定义标记单击事件侦听器 X 次。

另一种解释方式。想象一下,您没有循环,但您正在创建多个标记,如下所示:

        var marker = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: new google.maps.LatLng(point.target.x, point.target.y)
        });
        google.maps.event.addListener(marker, 'click', function (e) {
            toggleBounce(marker);
        });

        var marker = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: new google.maps.LatLng(point.target.x, point.target.y)
        });
        google.maps.event.addListener(marker, 'click', function (e) {
            toggleBounce(marker);
        });

您已经设法创建了两个标记(即使它们具有相同的变量名),但您所做的只是创建了一个事件侦听器函数,它只适用于这两个标记中的第二个。

如果相反,您已经完成了:

        var marker1 = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: new google.maps.LatLng(point.target.x, point.target.y)
        });
        google.maps.event.addListener(marker1, 'click', function (e) {
            toggleBounce(marker1);
        });

        var marker2 = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: new google.maps.LatLng(point.target.x, point.target.y)
        });
        google.maps.event.addListener(marker2, 'click', function (e) {
            toggleBounce(marker2);
        });

那么你有两个不同的事件监听器函数,用于两个不同的标记。因此,通过将其移到循环之外的自己的函数中,并将每个标记作为参数传递给该函数,您将为每个标记创建一个唯一的事件侦听器。说得通?

于 2013-05-24T09:04:38.450 回答