Mau*_*oni 1 google-maps scope angular
我正在使用Google Maps API v3,并且在我的地图上有一些多边形。我试图添加一个事件,单击将其全部删除,并在该事件的回调函数中调用另一个函数,但我不断收到TypeError:无法读取第64行上未定义的属性“ length”(即在事件侦听器及其告诉中我没有定义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();
});
}
}Run Code Online (Sandbox Code Playgroud)
您需要使用箭头功能()=>,而不是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();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
578 次 |
| 最近记录: |