You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 10 基于MapBox坐标渲染谷歌地图时报Cannot read property '0'错误

问题根源

  1. 异步逻辑执行顺序错误:searchGet 和 getCoords 都是异步请求,JS不会等请求返回就直接执行后续弹窗初始化代码,此时 this.center 还是未赋值的初始状态,访问 this.center[0] 自然抛出 undefined 错误。
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 13:45:08