Kenny Nguyen
Kenny Nguyen

Reputation: 232

JS google map modify listener from another class

I'm in the middle of converting my google map from ionic-native to JS. I'm trying to modify my map's click listener from another class. Howevever I'm getting property issues.

this.maps.init(); //Initialize map

this.maps.map.addListener('click', function(pos){

   this.maps.addMarker(pos.latLng.lat(), pos.latLng.lng());//error here

});

I'm getting the error

Cannot read property 'addMarker' of undefined

help please

Upvotes: 1

Views: 45

Answers (1)

sebaferreras
sebaferreras

Reputation: 44669

You just need to use arrow functions like this:

this.maps.init(); //Initialize map

this.maps.map.addListener('click', (pos) => {

   this.maps.addMarker(pos.latLng.lat(), pos.latLng.lng());//error here

});

By using arrow functions, the this property is not overwritten and still references the component instance.

Upvotes: 1

Related Questions