I have an Angular 2 project and am wanting to test event listeners. this is defined
map;
then in a populate map method i have
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);
}
an exception is thrown in the listener of
Uncaught TypeError: Cannot read property 'panTo' of undefined
Is there a reason why javascript is unable to find the correct "this.map" reference, forgot to mention, this is Google Maps API v3
I have an Angular 2 project and am wanting to test event listeners. this is defined
map;
then in a populate map method i have
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);
}
an exception is thrown in the listener of
Uncaught TypeError: Cannot read property 'panTo' of undefined
Is there a reason why javascript is unable to find the correct "this.map" reference, forgot to mention, this is Google Maps API v3
Share Improve this question asked Feb 16, 2017 at 15:01 user2168435user2168435 7622 gold badges10 silver badges28 bronze badges1 Answer
Reset to default 7You are inside of a different context and thus this
does not refer to the outer context. You have to keep a reference to it e.g.
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);
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745312097a4622045.html
评论列表(0条)