基于Leaflet框架的在线地图

昨晚和高中同学聊起web端地图,于是突发奇想借助ai和框架做一个简易的系统,以此证实如今ai的强大

项目结构如下

app.py用最典型的Flask框架

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from flask import Flask, render_template, jsonify

app = Flask(__name__)

mock_data = [
{
"name": "标注点 A",
"lat": 39.9042, # 北京示例坐标
"lng": 116.4074
},
{
"name": "标注点 B",
"lat": 31.2304, # 上海示例坐标
"lng": 121.4737
}
]

@app.route("/")
def index():
"""返回主页面"""
return render_template("index.html")

@app.route("/api/locations")
def get_locations():
"""返回地理数据(JSON)"""
return jsonify(mock_data)

if __name__ == "__main__":
app.run(port=5000, debug=True)

直接用Leaflet 资源的话会显示integrity校验失败,于是不使用 integrity等属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>地图演示页面</title>

<!-- 引入 Leaflet CSS (不使用 integrity 和 crossorigin 属性) -->
<link
rel="stylesheet"
href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"
/>

<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}" />
</head>
<body>

<header>
<h1>地图演示页面</h1>
</header>

<section id="map-section">
<!-- 地图容器 -->
<div id="map"></div>
</section>

<footer>
<p>© 2025 地图演示</p>
</footer>

<!-- 引入 Leaflet JS (不使用 integrity 和 crossorigin 属性) -->
<script
src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"
></script>

<!-- 引入主逻辑脚本 -->
<script src="{{ url_for('static', filename='main.js') }}"></script>

</body>
</html>
const map = L.map('map').setView([34, 108], 5);

// 设置 OpenStreetMap 瓦片层
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap',
maxZoom: 19,
}).addTo(map);

// 从后端获取地理数据
fetch('/api/locations')
.then(response => response.json())
.then(data => {
data.forEach(item => {
// 为每个地点添加一个标注点
const marker = L.marker([item.lat, item.lng]).addTo(map);
// 为标注点添加弹出框显示名称和坐标
marker.bindPopup(`<b>${item.name}</b><br>坐标: ${item.lat}, ${item.lng}`);
});
})
.catch(error => {
console.error("获取标注点数据失败:", error);
});
body {
margin: 0;
padding: 0;
font-family: "Microsoft YaHei", Arial, sans-serif;
background-color: #fafafa;
}

header, footer {
text-align: center;
background-color: #333;
color: #fff;
padding: 12px 0;
}

h1 {
margin: 0;
font-size: 24px;
}

/* 地图所在容器 */
#map-section {
width: 100%;
height: calc(100vh - 120px); /* 除去 header/footer 的高度 */
position: relative;
}

/* Leaflet 地图必须显式设置高度才能显示 */
#map {
width: 100%;
height: 100%;
}

最终效果

在大模型普及的今天,原来可能需要几天的时间来学习开发相关知识,现在只需要半小时就能完成基础开发,实在令人震惊。大模型在带给我们诸多便利的同时也给我带来一些思考:应该如何抵御ai浪潮的冲击,找到自己较为满意的工作?目前看来辩证看待ai给出的结果和持续学习应该是不错的选择,加油吧少年


基于Leaflet框架的在线地图
https://j1ya-22.github.io/2025/03/21/基于Leaflet框架的在线地图/
作者
j1ya
发布于
2025年3月21日
许可协议