欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > 在Angular中使用Leaflet构建地图应用

在Angular中使用Leaflet构建地图应用

2025/7/5 7:16:30 来源:https://blog.csdn.net/kongxx/article/details/147992204  浏览:    关键词:在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/

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词