Mauro Cappelloni
Mauro Cappelloni

Reputation: 143

Cant acces a variable from inside a function of an event listener / Angular 2

i am using google maps api v3 and have some polygons on my map. I am trying to add an event that on click deletes them all and calls another function inside the callback function for the event but i keep getting TypeError: Cannot read property 'length' of undefined on line 64 (thats inside the event listener and its telling me the Polys array its not defined). Also if i try to add a function inside the listener it wont recognize it, i figure it has to do with an scope problem but i dont know how to resolve it. Thanks for the help in advance.

export class InicioComponent implements OnInit, AfterViewInit {

  locaciones: Locacion[] = [];
  regiones: Region[];
  polys: any[] = [];
  constructor(private locacionService: LocacionService, private router: Router) { }

  getLocaciones(): void {
    this.locacionService.getLocaciones().then(locaciones => this.locaciones = locaciones);
  }

   public loadLocaciones(router: Router) {
    for (let i = 0; i < this.locaciones.length; i++) {
      const marker = new google.maps.Marker({
        position: new google.maps.LatLng(this.locaciones[i].latitud, this.locaciones[i].longitud),
        map: map,
        label: {
          color: 'black',
          fontWeight: 'bold',
          text: this.locaciones[i].nombre,
        },
        idLocacion: this.locaciones[i].id
      });
      google.maps.event.addListener(marker, 'click',() => {
        router.navigate(['/locacion', this.locaciones[i].id]);
      });
    }
  }
  getRegiones() {
    this.locacionService.getRegiones().then(regiones => {
      this.regiones = regiones;
      console.log(this.regiones);
    });
  }
  loadRegiones(regiones: Region[]) {
    for(let i = 0; i < regiones.length; i++) {
      const p = new google.maps.Polygon({
        paths: regiones[i].mapData.bounds,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35,
        idRegion: regiones[i].id
      });
      p.setMap(map);
      this.polys.push(p);
      google.maps.event.addListener(p, 'click', function(event){
        for( let j = 0; j < this.polys.length; j++) {
        this.polys[j].setMap(null);
        }
        this.loadLocaciones();

      });
    }
  }

Upvotes: 1

Views: 1346

Answers (1)

FAISAL
FAISAL

Reputation: 34683

You need to use arrow function ()=>, instead of the function keyword. When you use the function keyword, you loose scope to this. Change your code to this:

google.maps.event.addListener(p, 'click', (event) => {
    for( let j = 0; j < this.polys.length; j++) {
        this.polys[j].setMap(null);
    }
    this.loadLocaciones();
  });

Upvotes: 5

Related Questions