Contents

[Thought] Historical Earthquake Locations Around Taiwan

Contents
Tip
This project was written in January 2026.

After experiencing the April 3 Earthquake, I came up with the idea of visualizing earthquake information on a map. I searched both the Government Open Data Platform and the Open Weather Data Platform, and eventually found the Historical Earthquake Catalog (歷史地震目錄) on the Open Weather Data Platform.

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

After downloading the dataset, you will obtain a file named CWA-EQ-Catalog-{year}.xml. By reading it with the following Python script, you can generate a cleaned and organized dataset.

 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
The processed dataset.

The next step is to visualize the processed data. First, convert the original CSV file into JSON format using the following script.

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

The downloaded dataset contains numerous variables. My original plan was to combine the latitude, longitude, and depth information to create a 3D map, allowing each earthquake to be visualized with its spatial distribution in three dimensions. However, since I had no prior experience with 3D map development at the time, the implementation proved to be far more challenging than expected. As a result, I decided to scale back the scope and complete a 2D version first.

During development, I repeatedly experimented with different map styles and visualization approaches, but none of them achieved the result I had envisioned. Consequently, the project was eventually put on hold.

The following is the unfinished prototype that I completed at the time, which still has plenty of room for improvement. My initial goal was to integrate earthquake data from all years into a single HTML page, making it easy to browse the entire historical record. However, testing revealed that the dataset was simply too large, resulting in an oversized webpage, long loading times, and poor overall performance. I therefore changed the design to generate a separate page for each year instead.

I also planned to add an interactive feature that would allow users to select a date and play an animation showing earthquakes occurring over time, making it easier to observe how seismic activity changed across different periods. After implementing an initial version, however, I found that both the interaction and user experience fell short of my expectations, so this feature was ultimately left unfinished.

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

Later, I also discovered that the Taiwan Earthquake Science Information System already provides a similar interactive map. Not only is its dataset more comprehensive, but its interface design and user experience are also far more polished. As a result, I decided not to continue developing this project, bringing it to a natural conclusion.

https://Josh-test-lab.github.io/posts/Historical%20Earthquake%20Locations%20Around%20Taiwan/TESIS.webp
Taiwan Earthquake Science Information System.

References