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 地图,并在地图上添加了一个标记点。你可以根据自己的需求对地图进行进一步定制和添加其他图层。

相关推荐
GIS地信小匠1 天前
(31)ArcGIS Pro 定义投影与批量投影:矢量数据坐标转换工具实操
arcgis·空间分析·数据处理·gis教程·arcgls pro
非科班Java出身GISer1 天前
ArcGIS JS 基础教程(3):地图缩放、平移、旋转(基础交互)
arcgis·arcgis js地图交互·arcgis js缩放·arcgis js平移·arcgis js旋转·arcgis js基础交互
城数派2 天前
2025年我国省市县三级的平均坡度数据(Excel\Shp格式)
arcgis·信息可视化·数据分析·excel
装疯迷窍_A2 天前
以举证方位线生成工具为例,分享如何在Arcgis中创建Python工具箱(含源码)
开发语言·python·arcgis·变更调查·举证照片
Trustport3 天前
ArcGIS Maps SDK For Kotlin 加载Layout中的MapView出错
android·开发语言·arcgis·kotlin
GIS地信小匠3 天前
(30)ArcGIS Pro 查找相同项+删除相同项:矢量数据去重实操
arcgis·空间分析·数据处理·gis教程·arcgls pro
城数派3 天前
2025年我国乡镇的平均高程数据(Excel\Shp格式)
数据库·arcgis·信息可视化·数据分析·excel
城数派4 天前
2025年省市县三级的平均高程数据(Excel\Shp格式)
数据库·arcgis·信息可视化·excel
非科班Java出身GISer5 天前
ArcGIS JS 基础教程(2):地图切换底图(天地图)
arcgis·arcgis js天地图·arcgis js切换底图·arcgis js底图·arcgis js自定义底图·arcgis js自定义地图
城数派5 天前
2025年全国地级市间驾车出行距离和出行时间矩阵数据
数据库·arcgis·信息可视化·数据分析