地图标记单击目标错误标记

时间:2014-02-18 07:15:35

标签: javascript json google-maps-api-3 google-maps-markers typescript

所以我通过循环创建了几个Google Maps Marker并添加了应该打开相应infoWindow的点击监听器。但是,每次单击标记始终会打开最后添加的标记的infoWindow。

private loadMarkers():void {
    net.Ajax.getJson("/locations.json", (response:Location[]) => {
        for (var i = 0; i < response.length; i++) {
            var location:Location = response[i];
            var marker:google.maps.Marker = this.createMarker(location);
            google.maps.event.addListener(marker, 'click', () => {
                this.onMarkerClicked(marker);
            });
        }
    });
}

private onMarkerClicked(marker:google.maps.Marker):void {
    this.infoWindow.close();

    this.infoWindow = new google.maps.InfoWindow({
        content: marker.getTitle()
    });

    this.infoWindow.open(this.map, marker);
}

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

这是一个典型的闭包概念错误。闭包捕获变量marker而不是其值。由于变量范围是function,因此您只有一个marker

修复:创建immediately executing function(类似于打字稿中的module pattern)。

net.Ajax.getJson("/locations.json", (response:Location[]) => {
        for (var i = 0; i < response.length; i++) {
            (function(){
            var location:Location = response[i];
            var marker:google.maps.Marker = this.createMarker(location);
            google.maps.event.addListener(marker, 'click', () => {
                this.onMarkerClicked(marker);
            });
            })();
        }
    });

PS:我有关于这个主题的视频:http://www.youtube.com/watch?v=hU4cbxpe49Y&hd=1