【问题标题】:google maps dynamically created marker click event uses same marker谷歌地图动态创建的标记点击事件使用相同的标记
【发布时间】:2015-04-08 16:30:42
【问题描述】:

所以我有一个 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(marker) 始终是相同的标记。如何让听众添加特定的标记?

【问题讨论】:

  • marker 变量好像有问题。this.get('id') 返回什么?
  • 相同的 id (12) 即使我按下不同的标记。因为添加到 event.addListener 接缝的标记对于所有这些接缝都是相同的。

标签: javascript jquery google-maps google-maps-api-3


【解决方案1】:

似乎是闭包的问题..它总是返回最后一个知道的标记..您必须将点击处理程序的一部分带到一个新函数(外部)。

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

将 addEventListener 替换为 addClickHandler(marker);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 2017-04-27
    • 2012-09-27
    相关资源
    最近更新 更多