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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
| import os
import pandas as pd
import folium
from folium.plugins import TimestampedGeoJson
from datetime import datetime
# 1. 讀取 CSV
csv_file = r'E-A0073-002\earthquake_all_sorted.csv'
df = pd.read_csv(csv_file, parse_dates=['OriginTime'])
# 2. 輸出資料夾
output_folder = "earthquake_maps"
os.makedirs(output_folder, exist_ok=True)
# 3. 地圖背景
tileset = "OpenStreetMap"
# 4. 半徑依震級縮放
def magnitude_to_radius(mag):
return 2 * (2 ** (mag / 2))
# 5. 深度顏色函數
DEPTH_COLORS = [
(0, (255, 0, 0 )),
(10, (255, 128, 0 )),
(30, (255, 255, 0 )),
(50, (0, 255, 0 )),
(70, (0, 0, 255)),
(100, (128, 0, 128))
]
def depth_to_color(depth):
if depth <= 0:
return "rgba(255,0,0,1)"
if depth >= 100:
return "rgba(128,0,128,1)"
for i in range(len(DEPTH_COLORS) - 1):
d0, c0 = DEPTH_COLORS[i]
d1, c1 = DEPTH_COLORS[i + 1]
if d0 <= depth <= d1:
ratio = (depth - d0) / (d1 - d0)
r = int(c0[0] + ratio * (c1[0] - c0[0]))
g = int(c0[1] + ratio * (c1[1] - c0[1]))
b = int(c0[2] + ratio * (c1[2] - c0[2]))
return f"rgba({r},{g},{b},1)"
return "rgba(128,0,128,1)"
# 6. 震級顏色
def magnitude_to_color(mag):
if mag <= 2:
return "rgba(0,0,255,0.5)"
elif mag <= 4:
return "rgba(0,255,255,0.5)"
elif mag <= 5:
return "rgba(0,255,0,0.5)"
elif mag <= 6:
return "rgba(255,255,0,0.6)"
elif mag <= 7:
return "rgba(255,128,0,0.8)"
else:
return "rgba(255,0,0,1)"
# 7. 每年輸出地圖
for year, group in df.groupby(df['OriginTime'].dt.year):
features = []
eq_list = []
for _, row in group.iterrows():
day_start = datetime(row['OriginTime'].year, row['OriginTime'].month, row['OriginTime'].day)
ts_ms = int(day_start.timestamp() * 1000)
radius = magnitude_to_radius(row['LocalMagnitude'])
color_fill = depth_to_color(row['FocalDepth'])
color_border = magnitude_to_color(row['LocalMagnitude'])
feature = {
"type": "Feature",
"geometry": {"type": "Point", "coordinates": [row['EpicenterLongitude'], row['EpicenterLatitude']]},
"properties": {
"times": [ts_ms],
"style": {"color": color_border, "fillColor": color_fill, "radius": radius, "weight": 2},
"icon": "circle",
"popup": (
f"發生時間: {row['OriginTime']}<br>"
f"座標位置: 經度 {row['EpicenterLongitude']}, 緯度 {row['EpicenterLatitude']}<br>"
f"震央深度: {row['FocalDepth']} km<br>"
f"芮氏規模: {row['LocalMagnitude']}<br>"
f"觀測站數: {row['StationNumber']}"
)
}
}
features.append(feature)
# 傳給右側面板的資料
eq_list.append({
"time": row['OriginTime'].isoformat(),
"lat": row['EpicenterLatitude'],
"lon": row['EpicenterLongitude'],
"depth": row['FocalDepth'],
"mag": row['LocalMagnitude'],
"location": str(row.get("Location", "")),
"popup": feature['properties']['popup']
})
geojson = {"type": "FeatureCollection", "features": features}
# 地圖
m = folium.Map(location=[23.7, 121], zoom_start=8, tiles=tileset)
TimestampedGeoJson(
geojson,
period="P1D",
duration="P1D",
auto_play=True,
loop=False,
max_speed=20,
loop_button=True,
date_options='YYYY-MM-DD',
time_slider_drag_update=True
).add_to(m)
# 深度漸層
def generate_depth_gradient_css():
steps = []
for d in range(0, 101):
steps.append(f"{depth_to_color(d)} {d}%")
return "linear-gradient(to right, " + ", ".join(steps) + ")"
depth_gradient_css = generate_depth_gradient_css()
# 圖例
legend_html = f"""
<div style="
position: fixed;
bottom: 50px; left: 50px; width: 280px;
border:2px solid grey; z-index:9999; font-size:14px;
background-color:white; padding: 10px;
">
<b>深度 (圓心,公里)</b><br>
<div style="background: {depth_gradient_css}; width: 240px; height: 18px; margin-top:6px;"></div>
<div style="width:240px; font-size:12px; margin-top:2px;">
<span style="float:left;">0 km</span>
<span style="float:right;">100 km+</span>
</div><br>
<b>震級 (邊框)</b><br>
<div style="display:flex; margin-top:5px;">
<div style="text-align:center; width:40px;">
<div style="background-color: rgba(0,0,255,1); width:40px; height:15px;"></div>
<span style="font-size:12px;">0-2</span>
</div>
<div style="text-align:center; width:40px;">
<div style="background-color: rgba(0,255,255,1); width:40px; height:15px;"></div>
<span style="font-size:12px;">2-4</span>
</div>
<div style="text-align:center; width:40px;">
<div style="background-color: rgba(0,255,0,1); width:40px; height:15px;"></div>
<span style="font-size:12px;">4-5</span>
</div>
<div style="text-align:center; width:40px;">
<div style="background-color: rgba(255,255,0,1); width:40px; height:15px;"></div>
<span style="font-size:12px;">5-6</span>
</div>
<div style="text-align:center; width:40px;">
<div style="background-color: rgba(255,128,0,1); width:40px; height:15px;"></div>
<span style="font-size:12px;">6-7</span>
</div>
<div style="text-align:center; width:40px;">
<div style="background-color: rgba(255,0,0,1); width:40px; height:15px;"></div>
<span style="font-size:12px;">7+</span>
</div>
</div>
</div>
"""
m.get_root().html.add_child(folium.Element(legend_html))
# -----------------------------------------
# 右側面板 + 同步 TimestampedGeoJson
# -----------------------------------------
sidebar_js = f"""
<style>
#eqSidebar {{
position: fixed;
top: 0;
right: 0;
width: 320px;
height: 100vh;
background: white;
border-left: 2px solid #aaa;
box-shadow: -3px 0 8px rgba(0,0,0,0.3);
transform: translateX(0);
transition: transform 0.3s;
z-index: 9999;
font-family: Arial, sans-serif;
}}
#eqSidebar.collapsed {{
transform: translateX(280px);
}}
#eqSidebarHeader {{
background: #f0f0f0;
padding: 12px;
font-size: 15px;
font-weight: bold;
cursor: pointer;
border-bottom: 1px solid #ccc;
position: relative;
}}
#eqSidebarToggle {{
position: absolute;
right: 10px;
}}
#eqSidebarContent {{
padding: 12px;
overflow-y: auto;
height: calc(100vh - 55px);
}}
.eqItem {{
border-bottom: 1px solid #ddd;
padding: 8px 0;
}}
.eqTime {{
font-weight: bold;
}}
.eqInfo {{
font-size: 13px;
color: #444;
margin-top: 2px;
}}
</style>
<div id="eqSidebar">
<div id="eqSidebarHeader" onclick="toggleSidebar()">
今日地震列表(依時間)
<span id="eqSidebarToggle">⯇</span>
</div>
<div id="eqSidebarContent"></div>
</div>
<script>
const earthquakes = {eq_list};
function toggleSidebar() {{
const sb = document.getElementById("eqSidebar");
const tg = document.getElementById("eqSidebarToggle");
sb.classList.toggle("collapsed");
tg.textContent = sb.classList.contains("collapsed") ? "⯈" : "⯇";
}}
function updateSidebarByTime() {{
// 取得 TimestampedGeoJson 的當前播放時間
let tgLayer;
for (const key in window) {{
if (window[key] && window[key]._timeDimension) {{
tgLayer = window[key];
break;
}}
}}
if (!tgLayer) return;
const curTimeMs = tgLayer._timeDimension.getCurrentTime();
const curDate = new Date(curTimeMs);
// 篩選今天且早於或等於當前時間的地震
const list = earthquakes.filter(eq => {{
const t = new Date(eq.time);
return t.getFullYear() === curDate.getFullYear() &&
t.getMonth() === curDate.getMonth() &&
t.getDate() === curDate.getDate() &&
t <= curDate;
}}).sort((a,b)=> new Date(b.time) - new Date(a.time));
const panel = document.getElementById("eqSidebarContent");
panel.innerHTML = "";
if (list.length === 0) {{
panel.innerHTML = "<div>此時間點前無地震事件</div>";
return;
}}
list.forEach(eq => {{
const t = new Date(eq.time);
const timeStr = t.toLocaleTimeString("zh-TW", {{hour12:false}});
panel.innerHTML += `
<div class="eqItem">
<div class="eqTime">${{timeStr}}</div>
<div class="eqInfo">
${{eq.popup}}
</div>
</div>`;
}});
}}
setInterval(updateSidebarByTime, 500);
</script>
"""
m.get_root().html.add_child(folium.Element(sidebar_js))
# 儲存 HTML
html_file = os.path.join(output_folder, f"earthquake_map_{year}.html")
m.save(html_file)
print(f"{year} 年地震互動地圖已儲存為 {html_file}")
|