在Angular中使用Leaflet构建地图应用
Leaflet是一个用于创建地图的JavaScript库,它包含许多功能,并且非常适用于移动设备。
准备
nodejs: v20.15.0
npm: 10.7.0
angular: 19.2.10
创建一个地图应用工程
npx @angular/cli new my-leaflet-app --style=css --routing=false --skip-tests
提示 “Do you want to enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering)?” 的时候选择 No
创建完成后,启动一下,验证工程可以正常运行。
cd my-leaflet-app
npm start
然后访问 http://localhost:4200/ 验证。
安装leaflet
npm install leaflet @types/leaflet
创建地图组件
npx @angular/cli generate component map --skip-tests
编辑 map.component.ts 文件
import { Component, OnInit, AfterViewInit } from "@angular/core";
import * as leaflet from "leaflet";@Component({selector: "app-map",templateUrl: "./map.component.html",styleUrls: ["./map.component.css"],
})
export class MapComponent implements OnInit, AfterViewInit {map!: leaflet.Map;constructor() {}ngOnInit(): void {}ngAfterViewInit(): void {this.initMap();}private initMap(): void {this.map = leaflet.map("map").setView([51.5, -0.09], 13);const tiles = leaflet.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png",{maxZoom: 19,minZoom: 3,},);tiles.addTo(this.map);}
}
编辑 map.component.html 文件
<div class="map-container"><div class="map-frame"><div id="map"></div></div>
</div>
编辑 map.component.css 文件
.map-container {position: absolute;top: 0;left: 0;right: 0;bottom: 0;margin: 30px;
}.map-frame {border: 2px solid black;height: 300px;width: 500px;
}#map {height: 100%;
}
使用地图组件
编辑 app.component.ts 文件,导入地图组建
import { Component } from "@angular/core";
import { MapComponent } from "./map/map.component";@Component({selector: "app-root",imports: [MapComponent],templateUrl: "./app.component.html",styleUrl: "./app.component.css",
})
export class AppComponent {title = "my-leaflet-app";
}
编辑 app.component.html 文件,在视图中添加地图组件
<app-map></app-map>
最后修改 angular.json 文件,在编译选项中添加 “./node_modules/leaflet/dist/leaflet.css”,如下:
{"projects": {"my-leaflet-app": {"architect": {"build": {"options": {"styles": ["./node_modules/leaflet/dist/leaflet.css","src/styles.css"],},},}}}
}
验证
启动服务 npm start
,然后访问 http://localhost:4200/
。