1.在HTML文件中添加CSS样式代码:
#map {
height: 100%; /* 将高度设置为100% */
width: 100%; /* 将宽度设置为100% */
}
2.在Angular组件的ts文件中使用ViewChild来获取map div元素的引用。然后使用setSize方法调整地图大小以适应屏幕:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import * as L from 'leaflet';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {
@ViewChild('map') mapContainer: ElementRef;
map: any;
constructor() { }
ngOnInit() {
this.initMap();
}
initMap() {
this.map = L.map('map').setView([40.4168, -3.7038], 10); // 设置初始坐标和缩放级别
// 添加图层和控件等操作
this.map.on('load', () => {
this.map.invalidateSize(); // 调整地图大小以适应屏幕
});
}
}
3.在HTML文件中,在map div元素上使用Angular的内置指令ngAfterViewInit调用代码以确保地图在加载后被正确调整大小:
import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import * as L from 'leaflet';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit, AfterViewInit {
@ViewChild('map') mapContainer: ElementRef;
map: any;
constructor() { }
ngOnInit() {
this.initMap();
}
ngAfterViewInit() {
setTimeout(() => {
this.map.invalidateSize(); // 调整地图大小以适应屏幕
});
}
initMap() {
this.map = L.map('map').setView([40.4168, -3.7038], 10); // 设置初始坐标和缩放级别
// 添加图层和控件等操作