要解决Angular中谷歌地图在移动屏幕上只能第一次运行,然后变为空白的问题,可以尝试以下解决方法。
import { Component, AfterViewInit } from '@angular/core';
declare const google: any; // 如果没有引入Google地图的类型定义,可以使用declare声明
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent implements AfterViewInit {
map: any;
ngAfterViewInit(): void {
this.initMap();
}
initMap(): void {
const mapOptions = {
center: new google.maps.LatLng(37.7749, -122.4194),
zoom: 12
};
this.map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
}
请替换YOUR_API_KEY为您自己的Google地图API密钥。
import { Component, OnInit } from '@angular/core';
declare const google: any; // 如果没有引入Google地图的类型定义,可以使用declare声明
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {
map: any;
ngOnInit(): void {
this.initMap();
}
initMap(): void {
const mapOptions = {
center: new google.maps.LatLng(37.7749, -122.4194),
zoom: 12
};
this.map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
ngOnDestroy(): void {
// 在组件销毁时,清除地图对象,以便重新加载地图
this.map = null;
}
}
通过在ngOnDestroy生命周期钩子函数中清除地图对象,可以在切换到其他页面再切回来时重新加载地图。
使用以上解决方法之一,应该能够解决Angular中谷歌地图在移动屏幕上只能第一次运行,然后变为空白的问题。