3

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

3
  • Can you show your html page ? Commented Jun 8, 2018 at 6:55
  • <div id="map" class="map"></div> Commented Jun 8, 2018 at 8:58
  • 2
    Pradeep Join's answer was correct, it worked Commented Jun 8, 2018 at 8:59

1 Answer 1

6

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)
    });
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect solution! (regarding the downvoters, yes please justify yourself!)
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.