2017-02-16 115 views
1

我有一個Angular 2項目,我想測試事件監聽器。 這被定義typescript訪問監聽器中的全局變量

map; 

然後在填入映射方法,我有

populateMap() { 


var place = { lat: -17.822828, lng: -31.046727 }; 
this.map = new google.maps.Map(document.getElementById('map'), { 
    zoom: 12, 
    center: place, 
    mapTypeControlOptions: { 
    style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR, 
    position: google.maps.ControlPosition.TOP_RIGHT 
    }, 
    maxZoom: 19 
}); 


this.map.addListener('click', function (e) { 
var marker = new google.maps.Marker({ 
    position: e.latLng, 
    map: this.map 
    }); 
    this.map.panTo(e.latLng); 
}); 


this.map.fitBounds(this.bounds); 
this.map.panToBounds(this.bounds); 
} 

一個例外是在

Uncaught TypeError: Cannot read property 'panTo' of undefined 

聽衆扔有一個原因,JavaScript是無法找到正確的「this.map」參考,忘了提及,這是Google Maps API v3

回答

1

您位於不同的上下文中,因此this不引用外部上下文。你必須保留一個引用,例如

var self = this; 
this.map.addListener('click', function (e) { 
var marker = new google.maps.Marker({ 
    position: e.latLng, 
    map: self.map 
    }); 
    self.map.panTo(e.latLng); 
}); 
+0

輝煌,按預期工作。對於noob問題抱歉 – user2168435