Calling a function from a listener

Hi All,

It is probably simple javascript, but I am no expert. Can anyone assist me how I can call the function addMarker below from within the event listener? I am not sure why it can’t see the function.

Thanks

error:

TypeError: this.addMarker is not a function
this.addMarker(event.latLng);

code:

  loadMap() {
         .....
      this.map.addListener('click', function (event) {
        this.addMarker(event.latLng);
      });
  }
 addMarker(location) {
       .....
 }

This is the entire ts file:

import { Component } from '@angular/core';
import { Geolocation } from 'ionic-native';
import { NavController } from 'ionic-angular';
@Component({
  templateUrl: 'build/pages/map/map.html',
})
export class MapPage {
  private map: any;
  private google: any;
  private markers = [];
  constructor(private nav: NavController) {
    this.map = null;
    this.loadMap();
  }
  loadMap() {
    let options = {
      timeout: 10000,
      enableHighAccuracy: true
    };
    Geolocation.getCurrentPosition(options).then((position) => {
      let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      let mapOptions = {
        center: latLng,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      this.map = new google.maps.Map(document.getElementById("map"), mapOptions);
      // this.map.addListener('click', function (event) {
      //   this.addMarker(event.latLng);
      // });
      google.maps.event.addListener(this.map, 'click', function (event) {
        this.addMarker(event.latLng);
      })
    });
  }
  addInfoWindow(marker, content: string) {
    let infoWindow = new google.maps.InfoWindow({
      content: content
    });
    google.maps.event.addListener(marker, 'click', function () {
      infoWindow.open(this.map, marker);
    })
  }
  addMarker(location) {
    if (!location) {
      location = this.map.getCenter();
    }
    let marker = new google.maps.Marker({
      map: this.map,
      animation: google.maps.Animation.DROP,
      position: location
    });
    this.markers.push(marker);
    let content: string = 'remove';
    this.addInfoWindow(marker, content);
  }
  deleteAllMarkers() {
    this.clearMarkers();
    this.markers = [];
  }
  undoLastMarker() {
    let marker = this.markers.pop()
    if (marker) {
      marker.setMap(null);
    }
  }
  setMapOnAll(map) {
    for (var i = 0; i < this.markers.length; i++) {
      this.markers[i].setMap(map);
    }
  }
  clearMarkers() {
    this.setMapOnAll(null);
  }
}
this.map.addListener('click', (event) => {
    this.addMarker(event.latLng);
});
1 Like

Thank you, that works