【发布时间】:2018-02-17 11:37:48
【问题描述】:
我正在使用 google maps api v3 并且在我的地图上有一些多边形。我正在尝试添加一个事件,在单击时将它们全部删除并在事件的回调函数中调用另一个函数,但我不断收到 TypeError: Cannot read property 'length' of undefined on line 64(这在事件侦听器内部及其告诉我的 Polys 数组未定义)。此外,如果我尝试在侦听器中添加一个函数,它不会识别它,我认为它与范围问题有关,但我不知道如何解决它。 提前感谢您的帮助。
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();
});
}
}
【问题讨论】:
-
你最好参考这个问题 - stackoverflow.com/questions/36158848/…
标签: angular google-maps scope