Angular 10 基于MapBox坐标渲染谷歌地图时报Cannot read property '0'错误
问题根源
- 异步逻辑执行顺序错误:
searchGet和getCoords都是异步请求,JS不会等请求返回就直接执行后续弹窗初始化代码,此时this.center还是未赋值的初始状态,访问this.center[0]自然抛出 undefined 错误。 - setTimeout写法错误:setTimeout返回值是数字类型的计时器ID,不是回调里的坐标值,你把计时器ID传给point字段,地图组件拿到无效值自然渲染空白。
修复方案
第一步:调整nursery-search.component.ts的异步执行顺序
把弹窗初始化逻辑移到坐标请求成功的回调里,保证传值时坐标已经拿到:
// 修改后的MapDailog方法 MapDailog(nurserySearch) { this._nurseryService.searchGet(nurserySearch).subscribe((res) => { this.nurseryDetails = res; this.mapTitle = this.nurseryDetails.name + ", " + this.nurseryDetails.neighborhoodName; // 等日托详情返回后再查询坐标 this._HomeAppService.getPlace(this.nurseryDetails.neighborhoodName + "," + this.nurseryDetails.provinceName) .subscribe((features: Feature[]) => { // 加空值判断避免特殊情况报错 if(!features || features.length === 0) { // 此处可根据项目需求加无坐标提示 return; } this.center = features.map(feat => feat.center); // 坐标获取完成后再初始化弹窗 const config: ModalOptions = { initialState: { list: [{ nurserySearch: nurserySearch }], title: this.mapTitle, point: this.center[0], }, class: 'modal-lg map-container', animated: true, }; this.bsModalRef = this.modalService.show(MapModalComponent, config); this.bsModalRef.content.closeBtnName = 'Close'; }) }) }
原来的独立getCoords方法如果没有其他地方调用可以直接删除,避免逻辑冗余。
第二步:可选鲁棒性优化
给map-modal.component.ts加坐标有效性校验,避免极端场景报错:
ngOnInit(): void { // 先校验坐标有效性 if(!this.point || this.point.length < 2) { // 此处可根据项目需求加坐标无效提示 return; } console.log(this.point); console.log(this.list); this.options = { center: { lat: this.point[1], lng: this.point[0] }, zoom: 14 }; this.initOverlays(); this.infoWindow = new google.maps.InfoWindow(); }
修改完成后弹窗会等坐标成功返回才打开,不会再出现undefined报错,坐标传值正确后地图也能正常渲染。
内容的提问来源于stack exchange,提问作者Talha Khokhar
相关产品推荐
相关产品推荐

