Leaflet 中创建一个二维地图

要在 Leaflet 中创建一个二维地图,需要以下步骤:

1. 引入 Leaflet 库

首先,你需要在 HTML 文件中引入 Leaflet 库的 CSS 和 JavaScript 文件。你可以从官方网站下载 Leaflet,或者通过 CDN 引入。

html 复制代码
<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />

<!-- Leaflet JavaScript -->
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>

2. 创建地图容器

在 HTML 文件中创建一个 <div> 元素作为地图容器,指定一个唯一的 ID 用于在 JavaScript 中引用该地图。

html 复制代码
<div id="map" style="width: 100%; height: 400px;"></div>

3. 初始化地图

在 JavaScript 文件中使用 Leaflet 创建地图,并设置地图的中心位置和缩放级别。

javascript 复制代码
var map = L.map('map').setView([51.505, -0.09], 13); // 设置地图中心和缩放级别

4. 添加地图图层

Leaflet 支持添加不同类型的图层,比如瓦片图层(Tile Layer)、标记图层(Marker Layer)等。你可以从不同的服务提供商获取地图瓦片图层,比如 OpenStreetMap、Google Maps 等。

javascript 复制代码
// 添加 OpenStreetMap 图层
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
}).addTo(map);

5. 可选:添加标记

如果需要,在地图上添加标记点。

javascript 复制代码
var marker = L.marker([51.5, -0.09]).addTo(map);

6. 完整示例

下面是一个完整的示例代码:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Leaflet Map</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
    <style>
        #map { width: 100%; height: 400px; }
    </style>
</head>
<body>
    <div id="map"></div>

    <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
    <script>
        var map = L.map('map').setView([51.505, -0.09], 13);

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(map);

        var marker = L.marker([51.5, -0.09]).addTo(map);
    </script>
</body>
</html>

以上代码创建了一个基本的 Leaflet 地图,并在地图上添加了一个标记点。你可以根据自己的需求对地图进行进一步定制和添加其他图层。

相关推荐
行者-全栈开发6 小时前
【供应链攻击】CVE-2026-45321:TanStack供应链攻击漏洞深度解析与修复指南
arcgis
思特奇时空智能2 天前
大规模点要素地图渲染性能优化实践
vue.js·arcgis·性能优化·node.js·html·gis·webgl
上海懒图科技9 天前
工厂厂区电子地图定位导航:厂区人车精准定位,安全合规双保障
前端·arcgis·vue
非科班Java出身GISer13 天前
ArcGIS JS 基础教程(48):SceneView watch 状态监听
arcgis·arcgis js基础·arcgis js入门·arcgis js监听状态·arcgis js监听事件·arcgis js 监听飞行·arcgis js 监听功能
JudithHuang15 天前
React 嵌套路由与布局
前端·react.js·arcgis·react·react router
Dxy123931021616 天前
JS DES 加密详解
开发语言·javascript·arcgis
非科班Java出身GISer18 天前
ArcGIS JS 基础教程(46):编辑要素属性 FeatureForm
arcgis·arcgis js编辑要素·arcgis js 要素·arcgis js要素属性·arcgis js 编辑属性·arcgis js编辑要素属性
梅如你20 天前
ISPRS | 1990-2020年间中国人工林与天然林的空间分布数据
arcgis·gis·遥感
limit007523 天前
公开 WMTS / XYZ 瓦片接入 Cesium:6 类常见问题与排查顺序
chrome·低代码·arcgis·web3·旅游
limit007524 天前
三维模型悬空与切片偏移的排查顺序
低代码·3d·arcgis·web3·安卓·webgl