javascript - 如何以 Angular 显示多 map ?

标签 javascript angular google-maps ionic-framework

在我的 ionic 应用程序中,我想在同一页面中显示多个 map 。我的代码如下所示,但是,当我运行脚本时,出现错误:

Uncaught TypeError: Cannot read property 'nativeElement' of undefined
   at HomePage.webpackJsonp.982.HomePage.initMap

你能告诉我我的代码哪里错了吗?

首页.ts

maps: google.maps.Map[];
...
@ViewChild('map') mapElement;
...
initMap(i){
    let latLng = new google.maps.LatLng(100, 100);
    let mapOptions = {
      center: latLng,
      zoom:0,
      scrollwheel: true,
      zoomControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
    };
    this.maps[i]  =  new google.maps.Map(this.mapElement.nativeElement, 
      mapOptions);
 }

ionViewDidLoad() {
   setTimeout(()=>{
       for(var j=0;j<5;j++){
          initMap(j);
       }
   }, 5000)
}

主页.html

<ion-card  class="transparent-card" *ngFor="let number of [0,1,2,3,4]" >
  <div #map id="maps[number]" style="height:250px;"></div>
</ion-card>

最佳答案

您现在有五个标识符为 #map 的元素。

是否有某些原因导致您无法创建 MapComponent 并在组件的 ngOnInit 上初始化 map :

map 组件:

import { Component, ElementRef, OnInit } from '@angular/core';

@Component({
    selector: 'app-map',
    templateUrl: './app-map.html',
    styleUrls: ['./app-map.scss']
})
export class MapComponent implements OnInit {
    constructor(private readonly elem: ElementRef) {}

    map: google.maps.Map;

    ngOnInit(): void {
        let latLng = new google.maps.LatLng(100, 100);
        let mapOptions = {
            center: latLng,
            zoom: 0,
            scrollwheel: true,
            zoomControl: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        this.map = new google.maps.Map(
            this.elem.nativeElement,
            mapOptions
        );
    }
}

home.html

<ion-card *ngFor="let number of [0,1,2,3,4]">
  <app-map></app-map>
</ion-card>

关于javascript - 如何以 Angular 显示多 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57685881/

相关文章:

javascript - 使用 JQuery 获取所有样式属性。基本上我想要一个 getComputedStyle() 的等价物,我不想处理跨浏览器的东西

angular - 在编辑页面上预填充 formArray - Angular4

javascript - 单击外部链接时更改谷歌地图标记图标?

javascript - 带有透明字母的 SVG 背景以查看其他内容

javascript - Jcrop 没有正确裁剪图像

angular - Angular-5 登录后如何实现基于角色的重定向?

android - 如何将定位模式从默认模式更改为 "high accuracy/battery saving"(仅限设备)

android 如何在 map v2 上制作可拖动的图钉

javascript - jquery ajax 后刷新页面

angular - 将数组传递到 URLSearchParams,同时使用 get 请求的 http 调用