当前位置: 首页 > news >正文

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

相关文章:

  • 一招解决Tailwindcss4.x与其他库样式冲突问题
  • Scrapy框架下地图爬虫的进度监控与优化策略
  • 16.2 VDMA视频转发实验之模拟源
  • [Java实战]Spring Boot 3实现 RBAC 权限控制(二十五)
  • C# 实现雪花算法(Snowflake Algorithm)详解与应用
  • C++篇——多态
  • 知从科技闪耀2025上海车展:以创新驱动未来出行新篇章
  • redis解决常见的秒杀问题
  • STL?list!!!
  • “傅里叶变换算法”来检测纸箱变形的简单示例
  • 2025认证杯第二阶段数学建模B题:谣言在社交网络上的传播思路+模型+代码
  • Ruby 循环与迭代器
  • 图片爬虫通过模板及使用说明
  • 01-数据结构概述和时间空间复杂度
  • 数据驱动下的具身智能进化范式
  • 3DVR制作的工具或平台
  • 视差计算,求指导
  • [Java实战]Spring Boot + Netty 实现 TCP 长连接客户端及 RESTful 请求转发(二十六)
  • 3D曲面上的TSP问题(一):曲面上点集距离求解
  • 【Python 面向对象】
  • 丰富“互换通”产品类型,促进中国金融市场高水平对外开放
  • 体坛联播|博洛尼亚时隔51年再夺意杯,皇马逆转马洛卡
  • 消息人士称泽连斯基已启程前往土耳其
  • 浙能集团原董事长童亚辉被查,还是杭州市书法家协会主席
  • 上海国际电影节纪录片单元,还世界真实色彩
  • “大鼻子情圣”德帕迪约因性侵被判缓刑,还有新的官司等着他