目錄

【心得】臺灣周邊歷次地震位置圖

提示
本項目撰寫於 2026 年 1 月。

經歷 0403 地震後,就有將地震資訊轉為圖像呈現的想法。在搜尋政府開放資料平臺以及氣象資料開放平臺後,最後於氣象資料開放平臺找到歷史地震目錄

https://Josh-test-lab.github.io/posts/Historical%20Earthquake%20Locations%20Around%20Taiwan/歷史地震目錄.webp
歷史地震目錄。

待下載完後,會取得名為 CWA-EQ-Catalog-{year}.xml 的檔案,透過下列 Python 程式讀取,即可獲得整理後的檔案。

 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
import xml.etree.ElementTree as ET
import csv 
from pathlib import Path
from datetime import datetime

# XML 資料夾路徑
folder_path = Path('E-A0073-002')

# Namespace 定義
ns = {'cwa': 'urn:cwa:gov:tw:cwacommon:0.1'}

# 儲存所有地震資料
earthquake_list = []

# 遍歷資料夾內所有 XML
for xml_file in folder_path.glob('*.xml'):
    tree = ET.parse(xml_file)
    root = tree.getroot()
    
    for eq in root.findall('.//cwa:EarthquakeInfo', ns):
        origin_time_str = eq.findtext('cwa:OriginTime', default='', namespaces=ns)
        try:
            origin_time = datetime.fromisoformat(origin_time_str.replace('Z', '+00:00'))
        except ValueError:
            origin_time = None  # 若時間格式不正確
        
        earthquake_list.append({
            "OriginTime": origin_time_str,
            "OriginTime_dt": origin_time,  # 用於排序
            "EpicenterLongitude": eq.findtext('cwa:EpicenterLongitude', default='', namespaces=ns),
            "EpicenterLatitude": eq.findtext('cwa:EpicenterLatitude', default='', namespaces=ns),
            "FocalDepth": eq.findtext('cwa:FocalDepth', default='', namespaces=ns),
            "LocalMagnitude": eq.findtext('cwa:LocalMagnitude', default='', namespaces=ns).strip(),
            "StationNumber": eq.findtext('cwa:StationNumber', default='', namespaces=ns).strip(),
            "PhaseNumber": eq.findtext('cwa:PhaseNumber', default='', namespaces=ns).strip(),
            "MinimumEpicenterDistance": eq.findtext('cwa:MinimumEpicenterDistance', default='', namespaces=ns).strip(),
            "Gap": eq.findtext('cwa:gap', default='', namespaces=ns).strip(),
            "RMS": eq.findtext('cwa:rms', default='', namespaces=ns).strip(),
            "ERH": eq.findtext('cwa:erh', default='', namespaces=ns).strip(),
            "ERZ": eq.findtext('cwa:erz', default='', namespaces=ns).strip(),
            "Quality": eq.findtext('cwa:Quality', default='', namespaces=ns).strip(),
            "ReviewStatus": eq.findtext('cwa:ReviewStatus', default='', namespaces=ns).strip()
        })

# 依 OriginTime 排序
earthquake_list.sort(key=lambda x: x['OriginTime_dt'] or datetime.min)

# 寫入 CSV
csv_file = folder_path / 'earthquake_all_sorted.csv'
with open(csv_file, 'w', newline='', encoding='utf-8-sig') as f:
    writer = csv.writer(f)
    header = [
        "OriginTime", "EpicenterLongitude", "EpicenterLatitude", "FocalDepth",
        "LocalMagnitude", "StationNumber", "PhaseNumber", "MinimumEpicenterDistance",
        "Gap", "RMS", "ERH", "ERZ", "Quality", "ReviewStatus"
    ]
    writer.writerow(header)
    
    for eq in earthquake_list:
        writer.writerow([eq[h] for h in header])

print(f"CSV 已生成:{csv_file}")

https://Josh-test-lab.github.io/posts/Historical%20Earthquake%20Locations%20Around%20Taiwan/sorted_data.webp
經整理後的資料。

接下來便是將整理後的資料製成圖表了,以下先將原 CSV 檔案轉換為 JSON 格式。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import csv
import json

csv_file = "E-A0073-002/earthquake_all_sorted.csv"
json_file = "earthquake_all_sorted.json"

with open(csv_file, newline='', encoding='utf-8-sig') as f_in, open(json_file, 'w', encoding='utf-8') as f_out:
    reader = csv.DictReader(f_in)
    # 確認欄位
    print("欄位名稱:", reader.fieldnames)

    for row in reader:
        e = {
            "time": row["OriginTime"],
            "lat": float(row["EpicenterLatitude"]),
            "lon": float(row["EpicenterLongitude"]),
            "mag": float(row["LocalMagnitude"]),
            "depth": float(row["FocalDepth"])
        }
        # 每筆資料一行 JSON
        f_out.write(json.dumps(e, ensure_ascii=False) + "\n")

print(f"CSV 已轉成逐行 JSON: {json_file}")

下載的資料包含多項變數,原先欲結合經緯度與深度資訊,製成 3D 地圖,讓每次地震都能以立體方式呈現其空間分布。然而,對於當時尚未接觸過 3D 地圖製作的我而言,實作難度遠超出預期,因此最終退而求其次,先完成 2D 地圖的版本。

在製作過程中,雖然反覆調整了地圖樣式與呈現方式,但始終無法達到自己理想中的效果,因此這個專案最後便暫時擱置。

以下為當時完成的半成品程式碼,仍有許多可以改進的地方。最初希望將所有年份的地震資料整合至同一份 HTML 中,方便直接瀏覽完整的歷史紀錄,但實際測試後發現資料量過於龐大,導致網頁檔案過大、載入時間過長,整體效能不佳,因此後來改為依年份分別產生獨立的頁面。

此外,原本也曾規劃加入互動功能,讓使用者能直接在網站上選擇日期,播放地震事件隨時間發生的動畫,以觀察不同時期地震活動的變化。然而,在實作後認為互動效果與操作體驗皆未達預期,因此最終沒有將這項功能完成。

  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}")

而後來也發現,在台灣即時地震科學資訊系統中,已有相關類似的地圖可以使用,不僅資料更加完整,介面設計與互動體驗也更加成熟。因此,這個專案最後便沒有再繼續開發,也算是適時畫下句點。

https://Josh-test-lab.github.io/posts/Historical%20Earthquake%20Locations%20Around%20Taiwan/TESIS.webp
台灣即時地震科學資訊系統。

參考資料