谷歌地图动态创建的标记点击事件使用相同的标记



所以我有一篇ajax文章,它从我的数据库中获取了很多目的地。我对它们进行迭代,并在地图上为每一个添加一个标记。我还为它们中的每一个添加了一个点击事件,这样我就可以点击它们,但点击事件会得到作为输入创建的最后一个标记,所以无论我按下它们中的哪一个,我都会在点击事件中得到相同的标记。这是我的代码:

    success: function (data) {
        for (destination in data) {
            var latlng = { lat: data[destination].Latitude, lng: data[destination].Longitude }
            console.log(data[destination].Id);
            console.log(data[destination]);
            var marker = new google.maps.Marker({
                map: map,
                postion: new google.maps.LatLng(latlng.lat, latlng.lng),
            });
            marker.set("id", data[destination].Id);
            marker.setIcon( /** {google.maps.Icon} */({
                url: '/Content/Markers/green_MarkerX.png',
                size: new google.maps.Size(71, 71),
                origin: new google.maps.Point(0, 0),
                anchor: new google.maps.Point(17, 34),
                scaledSize: new google.maps.Size(35, 35)
            }));
            marker.setPosition(latlng);
            marker.setVisible(true);
            google.maps.event.addListener(marker, 'click', function () {
                console.log("MARKER");
                console.log(marker);
                console.log("MarkerID");
                console.log(marker.get('id'));
            });
        }
    },

console.log(marker.get('id'));始终相同,console.log(标记)始终相同。如何让侦听器添加特定的标记?

闭包似乎有问题。。它总是返回最后一个已知的标记。。您必须将clickhandler的一部分带到一个新函数(外部)。

信息:https://developers.google.com/maps/documentation/javascript/events?csw=1#EventClosures

将addEventListener替换为addClickHandler(标记);

function addClickHandler(theMarker) {
google.maps.event.addListener(theMarker, 'click', function() {
console.log(theMarker.get('id'));
  });
}

最新更新