要从latlng数组显示地图,我收到错误:"错误类型错误:无法读取未定义的属性'第一个孩子' "



我有一个 latlng 数组,我想从中显示我的角度组件上的地图。我用了QueryList<ElementRef>,但它给我抛出了错误类型错误:无法读取未定义的属性"firstChild">

在索引.html中,最后我用 defer 关键字应用了 maps.googleapis.com/maps/api/js 的正文标签。

这是我的代码:

@ViewChildren('gmap') gmapElement: QueryList<ElementRef>;

ngAfterViewInit() {
    setTimeout(() => {
      if(this.location && this.location.length) {
        this.location.forEach(location => {
          this.gmapElement.forEach(mapToDisplay => {
            const latlng = new google.maps.LatLng(location.latitude, location.longitude);
            var mapProp = {
              center: latlng,
              zoom: 15,
              // mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            console.log('prop... ',mapToDisplay.nativeElement);
            this.map = new google.maps.Map(mapToDisplay.nativeElement, mapProp);
          })
        })
      }
    }, 5000)
  }

在模板文件中,

<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5" *ngFor="let location of locations" style="border: solid black 1px">
    <ng-template #gmap class="g-map"></ng-template>
</div>

它把我扔了

"错误类型错误: 无法读取未定义的属性'第一个子'"。

请帮帮我

我想

我会跟进任何好奇为什么用div替换ng-template是修复方法的人:

根据 Angular 文档:

The <ng-template> is an Angular element for rendering HTML. It is never displayed 
directly. In fact, before rendering the view, Angular replaces the <ng-template> and 
its contents with a comment.

因此 #gmap 模板引用变量永远不会显示,因此永远不会在 ViewChildren 中选取。

您编写了代码以循环并在位置循环中创建 gmap。这就是所有地图都使用相同的位置的原因。

请尝试以下代码。

this.gmapElement.forEach((mapToDisplay, index) => {
  const location = this.location[index];
  const latlng = new google.maps.LatLng(location.latitude, location.longitude);
  var mapProp = {
    center: latlng,
    zoom: 15,
    // mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  console.log('prop... ',mapToDisplay.nativeElement);
  this.map = new google.maps.Map(mapToDisplay.nativeElement, mapProp);
});

最新更新