2017-09-08 11 views
1

Googleマップapi v3を使用していて、マップにポリゴンがいくつかあります。私はクリックでそれらをすべて削除し、イベントのコールバック関数内で別の関数を呼び出すイベントを追加しようとしていますが、TypeErrorを取得し続ける:64行目に未定義のプロパティ 'length'を読み込めません(イベントリスナーとそのPolys配列は定義されていません)。また、リスナーの内部に関数を追加しようとすると、それを認識することはできませんが、スコープの問題と関係していることがわかりますが、解決方法はわかりません。 事前に助けてくれてありがとう。カンタは、イベントリスナー/角2の関数の内部から変数にアクセスします。

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(); 
 

 
     }); 
 
    } 
 
    }

+0

あなたはより良いこの質問を参照してください - https://stackoverflow.com/questions/36158848/what-is-the-best-way-to-declare-a-global-variable - 角2小文字 – weBBer

答えて

1

かわりfunctionキーワードで、矢印機能()=>を使用する必要があります。 functionキーワードを使用すると、範囲がthisに緩和されます。これにあなたのコードを変更します。

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