1

因此,我通過循環創建了幾個Google地圖標記,並添加了應該打開相應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

這是一個經典的關閉概念錯誤。閉包捕獲變量不是其值。由於變量範圍是function,您只有一個。

修復:創建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