2

I'm using javascript Google Maps component in Angular 5 frontend framework

export class MapComponent implements OnInit {
  ngOnInit() {
    this.initializeGMap()
  }

  initializeGMap() {
    var myLatlng = new google.maps.LatLng(12,77);

    var mapOptions = {
        zoom: DEFAULT_MAP_ZOOM,
        center: myLatlng,
        scrollwheel: true,
        styles: MAP_STYLE
    };
    this.map = new google.maps.Map(document.getElementById("map"), mapOptions);
    this.initOnMapClickListener();
  }

  initOnMapClickListener() {
      google.maps.event.addListener(this.map, 'click', function(event) {

      var selectedLocation = new google.maps.LatLng(event.latLng.lat(), event.latLng.lng());
      this.addMarker(selectedLocation)
    });
  }

addMarker(latlng) {
    var marker = new google.maps.Marker({
      position: latlng,
      map: this.map,
      icon: './assets/map_marker.png'
    });
  }

}

Above is my typescript file, it has three functions

  1. initializeGMap() //to initialize google maps
  2. initOnMapClickListener() //to initialize on map click listener
  3. addMarker(latlng) // to add the marker when onmapclick event happens

Uncaught TypeError: Cannot read property 'addMarker' of null

this is what the console error I'm getting if I run Angular application

Please help to understand how to call a typescript function inside a Javascript callback

Cœur
  • 37,241
  • 25
  • 195
  • 267
Nandhakumar Appusamy
  • 1,156
  • 13
  • 22

1 Answers1

5

Try calling function using arrow function => like this to bind to the laxical scope of this -

initOnMapClickListener() {
      google.maps.event.addListener(this.map, 'click', (event) => {

      var selectedLocation = new google.maps.LatLng(event.latLng.lat(), event.latLng.lng());
      this.addMarker(selectedLocation)
    });
  }
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
  • 1
    Perfect solution! (regarding the downvoters, yes please justify yourself!) – Brain Oct 10 '19 at 17:21
  • Didn't downvote, but with complex scenarios this way you end up with functions that have hundreds if not thousands of lines of muddled code which are practically illegible. – JN01 May 19 '22 at 07:20