在我的 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/