目錄

Vibe Coding 協作小專案 - 臺灣縣市停班停課狀況地圖

封面圖片由 Google Gemini 生成。

在 AI 盛行的 2026 年,Vibe Coding 已經成為許多人常用的程式開發輔助方式。

Vibe Coding?

那麼,什麼是 Vibe Coding 呢?

簡單來說,就是由人類以自然語言提示(Prompt)的方式,向大型語言模型描述想要處理或解決的問題,再由模型生成或修改程式碼。如此一來,即使使用者不具備專業的程式設計背景,也能透過 AI 撰寫出可運作的程式。

心血來潮的項目

近期適逢颱風巴威襲臺,全臺各縣市無不討論是否應該放颱風假。無論是否放假,我都希望能快速知道所在地區是否因颱風而停止上班上課。

然而,我認為 行政院人事行政總處-天然災害停止上班及上課情形 網站所公布的資訊不夠直觀。當資料量一多時,往往無法迅速找到自己想查詢的縣市,因此便萌生了將文字資料轉換為視覺化地圖呈現的想法。

https://josh-test-lab.github.io/posts/Vibe%20Coding%20Collaboration%20Project/20260709_14.gif
巴威颱風預測路徑,取自 https://watch.ncdr.nat.gov.tw/watch_typhoon

雖然我熟悉使用 RPython 等統計程式語言,也略懂 HTML 的語法,但要撰寫從未深入鑽研的 JavaScript 仍然具有一定難度。

所幸現在 AI 已相當成熟,因此我決定將這次的小專案交由 AI 負責生成程式碼,而我則扮演「軍師」的角色,負責提出需求、審核程式、實際測試,以及回報功能缺失,讓 AI 持續修正。

最終,整個專案的主要功能僅花了 1 天便完成;若將後續的功能調整、錯誤修正與更新一併計算,也只花了約 3 天。如果沒有 AI 協助,光是查詢 JavaScript 語法、學習相關技術,以及尋找資料來源,整個專案大概需要花上 2 週左右才能完成。由此可見, Vibe Coding 確實能大幅縮短程式開發時間,並有效提升開發效率。

資料收集

https://josh-test-lab.github.io/posts/Vibe%20Coding%20Collaboration%20Project/open%20data.png
天然災害停止上班、停止上課情形公開資料。

首先,我查閱了相關的資料發布管道,發現政府其實已在政府資料開放平臺提供了天然災害停止上班、停止上課情形的公開資料。

此外,依據《政府資料開放授權條款》第二條第一項:

各機關所提供之開放資料,授權使用者不限目的、時間及地域、非專屬、不可撤回、免授權金進行利用,利用之方式包括重製、散布、公開傳輸、公開播送、公開口述、公開上映、公開演出、編輯、改作,包括但不限於開發各種產品或服務型態之衍生物。 因此,可以合法使用政府所提供的開放資料進行重製、改作及公開傳輸。我便決定以此資料為基礎,將原本的文字資訊改編成視覺化地圖,讓停班停課資訊能夠更直觀地呈現。

https://josh-test-lab.github.io/posts/Vibe%20Coding%20Collaboration%20Project/open%20data%20license.png
政府資料開放授權條款-第 1 版。

Vibe Coding

API 整理

本次專案使用 ChatGPT 免費版協助開發,一方面希望了解 OpenAI 所發展的大型語言模型目前的能力,另一方面也想驗證免費版是否已足以支援一般使用者進行小型專案開發。

首先,為了從 RSS Feed 擷取資料並進行前處理,在參考 《賴田捕手:番外篇》第 38 天:用 Netlify Functions 佈署 Line Bot 這篇文章後,我決定利用 Netlify Functions 提供的 Serverless 計算服務,擷取 天然災害停止上班、停止上課情形 的 RSS Feed https://alerts.ncdr.nat.gov.tw/RssAtomFeed.ashx?AlertType=33

接著,再由 Netlify Functions 將 RSS 資料解析、整理並轉換成網站所需的格式,供前端直接存取與使用。整理如下:

  • 整理前
 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
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:cap="urn:oasis:names:tc:emergency:cap:1.1" xmlns:georss="http://www.georss.org/georss">
<id>https://alerts.ncdr.nat.gov.tw/RSS.aspx</id>
<title>NCDR_CAP-即時防災資訊</title>
<updated>2026-07-12T22:14:00+08:00</updated>
<author>
<name>NCDR</name>
</author>
<rights>Public Domain</rights>
<link rel="self" href="https://alerts.ncdr.nat.gov.tw/RssAtomFeed.ashx?AlertType=33"/>
<entry>
<id>dgpa.gov.tw_workSchlClos_20260709202051_i_10017_001</id>
<title>停班停課</title>
<updated>2026-07-09T20:20:51+08:00</updated>
<author>
<name>行政院人事行政總處</name>
</author>
<link rel="alternate" href="https://alerts.ncdr.nat.gov.tw/Capstorage/DGPA/2026/workschoolclose_cap/dgpa.gov.tw_workSchlClos_20260709202051_i_10017_001.cap"/>
<summary type="html">[停班停課通知]基隆市:7/10停止上班、停止上課。行政院人事行政總處。如有任何問題請撥1999(市內直撥)。</summary>
<category term="停班停課"/>
<cap:status>Actual</cap:status>
<cap:msgType>Alert</cap:msgType>
<cap:effective>2026/7/9 下午 08:20:00</cap:effective>
<cap:expires>2026/7/10 上午 12:00:00</cap:expires>
</entry>
...
  • 整理後
 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
{
  "feedUpdated": "2026-07-12T22:14:00+08:00",
  "generatedAt": "2026-07-13T04:58:20.268Z",
  "areas": {
    "新竹縣": {
      "summary": [
        "[7/12] 新竹縣五峰鄉:今天已達停止上班及上課標準。"
      ],
      "alerts": [
        {
          "region": "五峰鄉",
          "summary": "新竹縣五峰鄉:今天已達停止上班及上課標準。",
          "updated": "2026-07-12T22:11:10+08:00",
          "effective": "2026/7/12 下午 10:10:00",
          "expires": "2026/7/13 上午 12:00:00",
          "link": "https://alerts.ncdr.nat.gov.tw/Capstorage/DGPA/2026/workschoolclose_cap/dgpa.gov.tw_workSchlClos_20260712221110_i_1000413_014.cap",
          "raw": {
            "id": "dgpa.gov.tw_workSchlClos_20260712221110_i_1000413_014",
            "title": "停班停課",
            "updated": "2026-07-12T22:11:10+08:00",
            "author": {
              "name": "行政院人事行政總處"
            },
            "link": {
              "rel": "alternate",
              "href": "https://alerts.ncdr.nat.gov.tw/Capstorage/DGPA/2026/workschoolclose_cap/dgpa.gov.tw_workSchlClos_20260712221110_i_1000413_014.cap"
            },
            "summary": {
              "#text": "[停班停課通知]新竹縣五峰鄉:今天已達停止上班及上課標準。行政院人事行政總處。如有任何問題請撥03-5513522#334~337。",
              "type": "html"
            },
            "category": {
              "term": "停班停課"
            },
            "cap:status": "Actual",
            "cap:msgType": "Update",
            "cap:effective": "2026/7/12 下午 10:10:00",
            "cap:expires": "2026/7/13 上午 12:00:00"
          }
        }
      ]
    },
    ...
  },
  "cache": true
}

如前所述,我對 JavaScript 並不熟悉,因此這部分的程式碼主要交由 ChatGPT 生成,而我則負責提出需求、檢查程式邏輯、實際測試,以及回報問題並持續修正。

在經過多次反覆調整、功能新增與除錯後,最終順利完成資料整理流程,並成功建置 API。為了降低 API 的回應時間及減少對遠端資料來源的存取次數,我另外設計了快取(Cache)機制,只要遠端資料未更新,API 便直接回傳既有的快取資料,而不重新擷取與解析 RSS Feed ,大幅提升了整體效能。

程式碼如下:

  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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
/**
 * NCDR 工作學校停課警報 (workschoolclose) 資料擷取與整理
 *
 * version: 2.4.2
 * date: 2026-07-11
 * 
 * ------------------------------------------------------------------------
 * 功能說明
 * ------------------------------------------------------------------------
 * 此 Netlify Function 會:
 *
 * 1. 抓取 NCDR(國家災害防救科技中心)提供的工作/學校停課 Atom Feed:
 *      https://alerts.ncdr.nat.gov.tw/RssAtomFeed.ashx?AlertType=33
 *
 * 2. 解析 Atom XML,保留所有原始欄位,並整理為 JavaScript 物件。
 *
 * 3. 依設定決定是否只保留最近兩天(今天與昨天)的資料:
 *      - 預設依 CONFIG.ONLY_TWO_DAYS
 *      - 可由 URL 參數 onlyTwoDays 覆蓋
 *
 * 4. 清理 summary:
 *      - 移除前導 "[停班停課通知]"
 *      - 移除 "行政院人事行政總處。" 之後所有文字
 *
 *      例如:
 *
 *      [停班停課通知]花蓮縣:7/10停止上班、停止上課。行政院人事行政總處。如有任何問題...
 *
 *      ↓
 *
 *      花蓮縣:7/10停止上班、停止上課。
 *
 * 5. 解析行政區資訊:
 *      county:縣市名稱
 *      region:行政區名稱
 *
 *      範例:
 *
 *      花蓮縣
 *          county = 花蓮縣
 *          region = 花蓮縣
 *
 *      臺東縣綠島鄉
 *          county = 臺東縣
 *          region = 綠島鄉
 *
 *      嘉義縣竹崎鄉
 *          county = 嘉義縣
 *          region = 竹崎鄉
 *
 * 6. 去除重複公告:
 *      使用
 *
 *          ${county}|${cleanedSummary}
 *
 *      作為唯一鍵,
 *      若有多筆相同公告,保留 updated 最新的一筆。
 *
 * 7. 將資料依縣市整理為 areas,
 *      並依 updated 由新到舊排序。
 *
 *      若某縣市沒有任何公告,
 *      自動加入預設公告:
 *
 *          "暫無公告 (No announcements)"
 *
 *      若 Feed 無法取得,
 *      則所有縣市皆回傳:
 *
 *          "無法取得資訊 (Unable to fetch data)"
 *
 * 8. 快取(Cache)機制:
 *      - 首次請求時建立 JSON 快取。
 *      - 後續請求會先比對 feedUpdated。
 *      - feedUpdated 相同則直接回傳快取。
 *      - feedUpdated 不同才重新解析 XML 並更新快取。
 *      - 可利用 forceRefresh=true 強制略過快取重新抓取。
 *
 * ------------------------------------------------------------------------
 * API
 * ------------------------------------------------------------------------
 *
 * 基本:
 *
 * GET /.netlify/functions/workschoolclose
 *
 * 回傳:
 *
 * {
 *     cache,
 *     feedUpdated,
 *     generatedAt,
 *     count,
 *     areas
 * }
 *
 * ------------------------------------------------------------------------
 * 可用參數
 * ------------------------------------------------------------------------
 *
 * county
 * ----------
 * 指定縣市。
 *
 * 範例:
 *
 * ?county=花蓮縣
 * ?county=花蓮縣,臺東縣
 *
 *
 * onlySummary
 * ----------
 * true
 *     只回傳 summary。
 *
 * false (預設)
 *     回傳完整 alerts。
 *
 * 範例:
 *
 * ?onlySummary=true
 * ?county=花蓮縣&onlySummary=true
 *
 *
 * onlyTwoDays
 * ----------
 * true
 *     僅保留今天與昨天資料。
 *
 * false
 *     不限制日期。
 *
 * 若未提供,
 * 則使用 CONFIG.ONLY_TWO_DAYS。
 *
 * 範例:
 *
 * ?onlyTwoDays=true
 * ?onlyTwoDays=false
 *
 *
 * forceRefresh
 * ----------
 * true
 *     強制重新抓取 Feed,
 *     忽略目前快取。
 *
 * false (預設)
 *     使用快取。
 *
 * 範例:
 *
 * ?forceRefresh=true
 *
 * ------------------------------------------------------------------------
 * API 使用範例
 * ------------------------------------------------------------------------
 *
 * 全部縣市
 * GET /.netlify/functions/workschoolclose
 *
 * 花蓮縣
 * GET /.netlify/functions/workschoolclose?county=花蓮縣
 *
 * 只回傳 Summary
 * GET /.netlify/functions/workschoolclose?onlySummary=true
 *
 * 花蓮縣 Summary
 * GET /.netlify/functions/workschoolclose?county=花蓮縣&onlySummary=true
 *
 * 查看全部 Feed(不限最近兩天)
 * GET /.netlify/functions/workschoolclose?onlyTwoDays=false
 *
 * 強制更新快取
 * GET /.netlify/functions/workschoolclose?forceRefresh=true
 *
 * 花蓮縣 + Summary + 強制更新
 * GET /.netlify/functions/workschoolclose?county=花蓮縣&summary=true&forceRefresh=true
 *
 * ------------------------------------------------------------------------
 * 相依套件
 * ------------------------------------------------------------------------
 *
 * npm install fast-xml-parser
 *
 * ------------------------------------------------------------------------
 * 注意事項
 * ------------------------------------------------------------------------
 *
 * - 本程式使用 Asia/Taipei 時區進行日期判斷。
 * - Feed 更新時間若超過兩天(且 onlyTwoDays=true),
 *   將所有縣市視為「暫無公告 (No announcements)」。
 * - API 回傳的 cache 欄位表示本次是否直接使用快取資料。
 */

import { XMLParser } from 'fast-xml-parser';
import fs from 'fs';

// --- 設定參數 (可依需求調整) ---
const CONFIG = {
    FEED_URL: "https://alerts.ncdr.nat.gov.tw/RssAtomFeed.ashx?AlertType=33", // NCDR Atom Feed
    ONLY_TWO_DAYS: true,        // 是否只保留今天/昨天的資料 (只篩選最新兩日資料)
    COUNTIES: [
        "臺北市", "新北市", "桃園市", "臺中市", "臺南市", "高雄市", "基隆市", "新竹市", "嘉義市", "新竹縣", "苗栗縣", "彰化縣", "南投縣", "雲林縣", "嘉義縣", "屏東縣", "宜蘭縣", "花蓮縣", "臺東縣", "澎湖縣", "金門縣", "連江縣"
    ],
    // 快取檔案 (執行時寫入 /tmp 目錄,注意該目錄非永久存儲)
    CACHE_FILE: "/tmp/workschoolclose.json"
};

/**
 * 下載並解析 Atom Feed,回傳物件 (含 feed 及 entry 陣列)
 */
async function fetchFeed() {
    const res = await fetch(CONFIG.FEED_URL);
    if (!res.ok) {
        throw new Error(`無法下載 RSS 資料 (狀態 ${res.status})`);
    }
    const xmlText = await res.text();
    // 解析 XML
    const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: "" });
    const feedObj = parser.parse(xmlText);
    return feedObj;
}

/**
 * 清理 summary 文字:
 *  - 移除前導的 [停班停課通知]
 *  - 移除「行政院人事行政總處。」之後的所有內容
 */
function cleanSummary(text) {
    let s = text || "";
    s = s.replace(/^\[[^\]]+\]/, "");
    s = s.replace(/行政院人事行政總處。[\s\S]*$/, "");
    return s.trim();
}

/**
 * 從清理後 summary 擷取縣市 (county) 與行政區 (region)
 * 例如 "臺東縣綠島鄉:xxx" -> county = "臺東縣", region = "綠島鄉"
 * 如果沒有子區域,region = county
 */
function parseRegion(cleaned) {
    const fullRegion = (cleaned.split(":")[0] || "").trim();
    let county = fullRegion;
    let region = fullRegion;
    for (const c of CONFIG.COUNTIES) {
        if (fullRegion.startsWith(c)) {
            county = c;
            // 如果子區域存在,取 substring;否則仍然是縣市名
            region = fullRegion.substring(c.length) || c;
            break;
        }
    }
    return { county, region };
}

/**
 * 去除重複公告 (相同縣市+清理後 summary),僅保留 updated 最新的那筆
 */
function deduplicateAlerts(alerts) {
    const latestMap = new Map();
    for (const alert of alerts) {
        const key = `${alert.county}|${alert.cleanedSummary}`;
        if (!latestMap.has(key) ||
            new Date(alert.updated) > new Date(latestMap.get(key).updated)) {
            latestMap.set(key, alert);
        }
    }
    return Array.from(latestMap.values());
}

/**
 * 依縣市分組,並加上 summary 清單
 * 若某縣市無公告,插入預設值 "暫無公告 (No announcements)"
 * 同時將每筆 alerts 依 updated 由近到遠排序,再產生對應的 summary list
 */
function groupByCounty(alerts) {
    const areas = {};
    // 初始化所有縣市
    for (const c of CONFIG.COUNTIES) {
        areas[c] = { summary: [], alerts: [] };
    }
    // 分組
    for (const alert of alerts) {
        if (!areas[alert.county]) {
            // 忽略未列入清單的縣市
            continue;
        }
        areas[alert.county].alerts.push({
            region: alert.region,
            summary: alert.cleanedSummary,
            updated: alert.updated,
            effective: alert.effective,
            expires: alert.expires,
            link: alert.link,
            raw: alert.raw
        });
    }
    // 處理各縣市的空置與排序
    for (const c of CONFIG.COUNTIES) {
        if (areas[c].alerts.length === 0) {
            // 若無公告,加入一筆預設訊息
            areas[c].alerts.push({
                region: c,
                summary: "暫無公告 (No announcements)",
                updated: "",
                effective: "",
                expires: "",
                link: "",
                raw: {}
            });
        }
        // 依 updated 時間從近到遠排序
        areas[c].alerts.sort((a, b) => new Date(b.updated) - new Date(a.updated));
        // 建立 summary 字串列表 (前綴 [月/日])
        areas[c].summary = areas[c].alerts.map(a => {
            if (!a.updated) {
                // 沒有有效時間,直接回傳原始 summary
                return a.summary;
            }
            const date = new Date(a.updated).toLocaleDateString("zh-TW", {
                timeZone: "Asia/Taipei", month: "numeric", day: "numeric"
            });
            return `[${date}] ${a.summary}`;
        });
    }
    return areas;
}

/**
 * 根據縣市篩選區域資料
 * 適用於 ?county= 花蓮縣,臺東縣 這種情況
 */
function filterAreasByCounty(areas, queryCounty) {
    if (!queryCounty) {
        return areas;
    }

    const counties = queryCounty
        .split(",")
        .map(c => c.trim());

    const selectedAreas = {};

    counties.forEach(county => {
        if (areas[county]) {
            selectedAreas[county] = areas[county];
        }
    });

    return selectedAreas;
}

/**
 * 根據縣市篩選區域資料,僅保留 summary 清單
 */
function extractSummaryAreas(areas) {

    const summaryAreas = {};

    Object.entries(areas).forEach(([county, data]) => {
        summaryAreas[county] = {
            summary: data.summary || []
        };
    });

    return summaryAreas;
}

/**
 * 載入快取 (若檔案存在),回傳 JSON 物件或 null
 */
function loadCache() {
    try {
        const raw = fs.readFileSync(CONFIG.CACHE_FILE, "utf8");
        return JSON.parse(raw);
    } catch (err) {
        return null;
    }
}

/**
 * 儲存快取至檔案 (JSON),寫入 /tmp 資料夾
 */
function saveCache(data) {
    try {
        fs.writeFileSync(CONFIG.CACHE_FILE, JSON.stringify(data));
    } catch (err) {
        console.error("快取保存失敗:", err);
    }
}

/**
 * Netlify Function 主程式
 */
export default async function handler(request) {
    // 嘗試讀取快取
    const cacheData = loadCache();
    // 解析查詢參數
    const url = new URL(request.url);
    /* 是否指定縣市 (county) */
    const queryCounty = url.searchParams.get('county');
    /* 是否只會傳回 summary 清單 (不含 alerts 陣列) */
    const summaryOnly = url.searchParams.get('onlySummary') === 'true';
    /* 是否只保留最近兩天的資料, url 參數優先於 CONFIG 設定 */
    const onlyTwoDays =
        url.searchParams.has("onlyTwoDays")
            ? url.searchParams.get("onlyTwoDays") === "true"
            : CONFIG.ONLY_TWO_DAYS;
    /* 是否強制重新抓取 Feed ,否則若快取存在且 Feed 未更新,直接回傳快取內容 */
    const forceRefresh = url.searchParams.get("forceRefresh") === "true";

    try {
        // 1. 下載並解析 Atom Feed
        const feedObj = await fetchFeed();
        const feedUpdated = feedObj.feed?.updated || "";

        // 若未要求強制更新,且 Feed 更新時間與快取一致,則直接回傳快取內容。
        if (!forceRefresh && cacheData && cacheData.feedUpdated === feedUpdated) {

            if (queryCounty || summaryOnly) {

                const selectedAreas = queryCounty
                    ? filterAreasByCounty(cacheData.areas, queryCounty) // 有指定縣市
                    : cacheData.areas;  // 所有縣市 (未指定縣市,但可能只要求 summaryOnly)

                if (Object.keys(selectedAreas).length === 0) {
                    return new Response(
                        JSON.stringify({
                            error: "Unknown county",
                            cache: true
                        }),
                        {
                            status:404,
                            headers:{
                                "Content-Type":"application/json; charset=utf-8",
                                "Access-Control-Allow-Origin":"*",
                                "Access-Control-Allow-Methods":"GET, OPTIONS",
                                "Access-Control-Allow-Headers":"Content-Type"
                            }
                        }
                    );
                }

                const outputAreas = summaryOnly
                    ? extractSummaryAreas(selectedAreas)
                    : selectedAreas;
                const summaries = Object.values(outputAreas)
                                        .flatMap(area => area.summary || []);
                return new Response(
                    JSON.stringify({
                        feedUpdated: cacheData.feedUpdated,
                        generatedAt: cacheData.generatedAt,
                        count: summaryOnly ? summaries.length : undefined,
                        areas: outputAreas,
                        cache: true
                    }),
                    {
                        status: 200,
                        headers: {
                            "Content-Type": "application/json; charset=utf-8",
                            "Access-Control-Allow-Origin":"*",
                            "Access-Control-Allow-Methods":"GET, OPTIONS",
                            "Access-Control-Allow-Headers":"Content-Type"
                        }
                    }
                );
            }

            // 預設回傳完整快取 (未指定任何參數)
            return new Response(
                JSON.stringify({
                    ...cacheData,
                    cache: true
                }),
                {
                    status: 200,
                    headers: {
                        "Content-Type": "application/json; charset=utf-8",
                            "Access-Control-Allow-Origin":"*",
                            "Access-Control-Allow-Methods":"GET, OPTIONS",
                            "Access-Control-Allow-Headers":"Content-Type"
                    }
                }
            );
        }

        // 2. 提取所有 entry,轉為警報物件 (含清理後 summary)
        const entries = feedObj.feed.entry || [];
        const alerts = entries.map(e => {
            const rawSummary = (typeof e.summary === "object") ? (e.summary["#text"] || "") : (e.summary || "");
            const cleaned = cleanSummary(rawSummary);
            const { county, region } = parseRegion(cleaned);
            return {
                raw: e,
                updated: e.updated || "",
                summary: rawSummary,
                cleanedSummary: cleaned,
                county: county,
                region: region,
                effective: e["cap:effective"] || "",
                expires: e["cap:expires"] || "",
                link: (e.link && (e.link.href || e.link)) || ""
            };
        });

        // 3. 篩選「今天」與「昨天」的資料 (依照 ?onlyTwoDays 參數決定)
        let filtered = alerts;
        if (onlyTwoDays) {
            const today = new Date().toLocaleDateString("sv-SE", { timeZone: "Asia/Taipei" });
            const yesterdayDate = new Date();
            yesterdayDate.setDate(yesterdayDate.getDate() - 1);
            const yesterday = yesterdayDate.toLocaleDateString("sv-SE", { timeZone: "Asia/Taipei" });
            filtered = alerts.filter(a => {
                const aDate = new Date(a.updated).toLocaleDateString("sv-SE", { timeZone: "Asia/Taipei" });
                return (aDate === today || aDate === yesterday);
            });
        }

        // 4. 去除重複公告
        const uniqueAlerts = deduplicateAlerts(filtered);

        // 5. 依縣市分組
        let areas = groupByCounty(uniqueAlerts);

        // 6. 若 Feed 資料超過 2 天未更新,全部視為「暫無公告」
        const now = new Date();
        const feedTime = new Date(feedUpdated);
        if (onlyTwoDays && feedUpdated && (now - feedTime > 2 * 24 * 60 * 60 * 1000)) {
            const emptyAreas = {};
            for (const c of CONFIG.COUNTIES) {
                emptyAreas[c] = {
                    summary: ["暫無公告 (No announcements)"],
                    alerts: [{
                        region: c,
                        summary: "暫無公告 (No announcements)",
                        updated: "",
                        effective: "",
                        expires: "",
                        link: "",
                        raw: {}
                    }]
                };
            }
            const resultEmpty = {
                feedUpdated: feedUpdated,
                generatedAt: new Date().toISOString(),
                count: 0,
                areas: emptyAreas
            };
            // 不更新快取,直接回傳結果
            return new Response(
                JSON.stringify({
                    ...resultEmpty,
                    cache: false
                }),
                {
                    status: 200,
                    headers: {
                        "Content-Type": "application/json; charset=utf-8",
                            "Access-Control-Allow-Origin":"*",
                            "Access-Control-Allow-Methods":"GET, OPTIONS",
                            "Access-Control-Allow-Headers":"Content-Type"
                    }
                }
            );
        }

        // 計算總筆數
        const totalCount = uniqueAlerts.length;

        // 7. 建構回傳 JSON
        let resultData = {
            feedUpdated: feedUpdated,
            generatedAt: new Date().toISOString(),
            count: totalCount,
            areas: areas
        };
        // 保存快取
        saveCache(resultData);

        // 8. 處理 ?county= 和 ?summary=true 參數
        if (queryCounty || summaryOnly) {

            const selectedAreas = queryCounty
                ? filterAreasByCounty(areas, queryCounty)  // 有指定縣市
                : areas;  // 所有縣市 (未指定縣市,但可能只要求 summaryOnly)

            if (Object.keys(selectedAreas).length === 0) {
                return new Response(
                    JSON.stringify({
                        error: "Unknown county",
                        cache: false
                    }),
                    {
                        status: 404,
                        headers: {
                            "Content-Type": "application/json; charset=utf-8",
                            "Access-Control-Allow-Origin":"*",
                            "Access-Control-Allow-Methods":"GET, OPTIONS",
                            "Access-Control-Allow-Headers":"Content-Type"
                        }
                    }
                );
            }

            if (summaryOnly) {

                const summaryAreas = extractSummaryAreas(
                    selectedAreas
                );

                const summaries = Object.values(summaryAreas)
                                        .flatMap(area => area.summary || []);

                return new Response(
                    JSON.stringify({
                        feedUpdated: resultData.feedUpdated,
                        generatedAt: resultData.generatedAt,
                        count: summaries.length,
                        areas: summaryAreas,
                        cache: false
                    }),
                    {
                        status: 200,
                        headers: {
                            "Content-Type": "application/json; charset=utf-8",
                            "Access-Control-Allow-Origin":"*",
                            "Access-Control-Allow-Methods":"GET, OPTIONS",
                            "Access-Control-Allow-Headers":"Content-Type"
                        }
                    }
                );
            }

            // 非 summary 模式,只保留指定縣市完整資料
            resultData.areas = selectedAreas;
        }

        // 正常回傳
        return new Response(
            JSON.stringify({
                ...resultData,
                cache: false
            }),
            {
                status: 200,
                headers: {
                    "Content-Type": "application/json; charset=utf-8",
                    "Access-Control-Allow-Origin":"*",
                    "Access-Control-Allow-Methods":"GET, OPTIONS",
                    "Access-Control-Allow-Headers":"Content-Type"
                }
            }
        );

    } catch (err) {
        console.error("Error:", err);
        // 若抓取失敗但有快取,則回傳快取內容
        if (cacheData) {
            return new Response(
                JSON.stringify({
                    ...cacheData,
                    cache: true,
                    error: "Fetch failed, returning cached data"
                }),
                {
                    status: 200,
                    headers: {
                        "Content-Type": "application/json; charset=utf-8",
                        "Access-Control-Allow-Origin":"*",
                        "Access-Control-Allow-Methods":"GET, OPTIONS",
                        "Access-Control-Allow-Headers":"Content-Type"
                    }
                }
            );
        }
        // 完全失敗時,回傳「無法取得資訊」預設訊息
        const errorAreas = {};
        for (const c of CONFIG.COUNTIES) {
            errorAreas[c] = {
                summary: ["無法取得資訊 (Unable to fetch data)"],
                alerts: [{
                    region: c,
                    summary: "無法取得資訊 (Unable to fetch data)",
                    updated: "",
                    effective: "",
                    expires: "",
                    link: "",
                    raw: {}
                }]
            };
        }
        const errorBody = {
            feedUpdated: "",
            generatedAt: new Date().toISOString(),
            count: 0,
            areas: errorAreas
        };
        return new Response(
            JSON.stringify({
                ...errorBody,
                cache: false
            }),
            {
                status: 200,
                headers: {
                    "Content-Type": "application/json; charset=utf-8",
                    "Access-Control-Allow-Origin":"*",
                    "Access-Control-Allow-Methods":"GET, OPTIONS",
                    "Access-Control-Allow-Headers":"Content-Type"
                }
            }
        );
    }
}

視覺化呈現

完成資料整理後,接下來便是最重要的視覺化呈現。

這部分同樣由 ChatGPT 協助生成 HTML 、 JavaScript 與 CSS 程式碼,再搭配 OpenStreetMap 提供的地圖底圖,以及 Taiwan.md 所提供的臺灣行政區域界線資料,繪製出各縣市行政區範圍,並以不同顏色標示各縣市的停班停課狀態。每個具有顏色的行政區皆可點擊,查看該縣市最新的停班停課公告內容。

此外,也設置了公告顯示欄位,依照公告發布時間排序,方便使用者快速瀏覽最新資訊。

https://josh-test-lab.github.io/posts/Vibe%20Coding%20Collaboration%20Project/final%20work.png
臺灣縣市停班停課狀況地圖

最終完成的成果,不僅能一眼辨識各縣市的停班停課狀況,也能透過點擊地圖與公告列表快速取得完整資訊。

相關的 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
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">

<style>
    /* 地圖區域 */
    #map {
        width: 100%;
        height: 600px;
        border-radius: 10px;
        z-index: 50;
    }

    /* 更新按鈕與狀態框 */
    .refresh-panel {
        display: inline-flex;
        align-items: center;
        gap: 12px;
        width: 100%;
        max-width: 100%;
        padding: 3px 14px;
        margin-bottom: 16px;
        box-sizing: border-box;
        background: #e6e6e6;
        border-radius: 8px;

        [theme=dark] & {
            background-color: #1a1d23;
        }
    }

    /* 更新按鈕 */
    .refresh-panel button {
        padding: 8px 18px;
        font-size: 15px;
        font-weight: 500;
        background: #ffffff;      /* 藍色 */
        border: 1px solid black;
        border-radius: 8px;
        cursor: pointer;
        transition: background .2s ease, transform .15s ease;

        [theme=dark] & {
            background: black;
            border: 1px solid #77777f;
            color: white;
        }

        &:active {
            transform: scale(0.97);
        }
    }

    /* 狀態文字 */
    .refresh-panel .status {
        white-space: nowrap;
    }

    /* ===== Leaflet 圖例 ===== */
    .legend {
        background: white;
        padding: 10px;
        line-height: 22px;
        box-shadow: 0 0 5px #999;
    }

    .legend i {
        width: 18px;
        height: 18px;
        float: left;
        margin-right: 8px;
    }

    /* Tooltip 樣式 */
    .leaflet-tooltip {
        font-size: 14px;
        line-height: 1.5;
        padding: 8px;
        border-radius: 10px;
    }

    .leaflet-tooltip b {
        font-size: 16px;
    }

    /* 手機版 */
    @media(max-width:600px) {
        #map {
            height: 70vh;
        }
        .alerts-panel {
            max-height:20vh;
        }
    }

    /* 公告面板 */
    .alerts-panel {
        width: 100%;
        max-width: 100%;
        padding: 8px 14px;
        margin-bottom: 16px;
        box-sizing: border-box;
        background: #e6e6e6;
        border-radius: 8px;
        max-height: 180px;
        overflow-y: auto;
        font-size: 0.9rem;
        line-height: 1.5;
        [theme=dark] & {
            background-color: #1a1d23;
        }
    }

    /* 每一筆公告 */
    .alert-item {
        padding: 6px 0;
        color: #333;
        display: flex;
        align-items: baseline;
        gap: 8px;
        line-height: 1.5;
        word-break: break-word;
        [theme=dark] & {
            color: #ddd;
        }
    }

    /* 時間 */
    .alert-item b {
        flex-shrink: 0;
        font-size: 0.8rem;
        font-weight: 600;
        color: #555;
        [theme=dark] & {
            color: #aaa;
        }
    }

    /* 公告內容 */
    .alert-item {
        word-break: break-word;
    }

    /* 分隔線 */
    .alerts-panel hr {
        border: 0;
        border-top: 1px solid rgba(0,0,0,0.15);
        margin: 4px 0;
        [theme=dark] & {
            border-top-color: rgba(255,255,255,0.15);
        }
    }

    /* scrollbar 美化 */
    .alerts-panel::-webkit-scrollbar {
        width: 6px;
    }

    .alerts-panel::-webkit-scrollbar-thumb {
        background: rgba(120,120,120,0.5);
        border-radius: 10px;
    }
</style>

<div class="refresh-panel">
  <button id="refresh">
      更新資訊
  </button>

  <span class="status" id="status">
      資料載入中...
  </span>
</div>
<div id="map"></div>

<!-- Leaflet JS -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

<!-- TopoJSON 轉 GeoJSON -->
<script src="https://unpkg.com/topojson-client@3"></script>

<!-- 視覺化地圖資訊 -->
<script>
    /*
    ==================================================
    基本設定
    ==================================================
    */
    const apiUrl = "你的 API";
    let data = null;
    // API 是否錯誤
    let errorFlag = false;
    // 縣市 GeoJSON 圖層
    let geojsonLayer = null;
    // 鄉鎮市區 GeoJSON 圖層
    let townLayer = null;
    // 快取日期鍵值
    const cacheKey = "workSchoolUpdateDay";

    /*
    ==================================================
    縣市代碼
    對應 taiwan.md 鄉鎮 topojson https://taiwan.md/taiwan-shape/
    ==================================================
    */
    const countyCode = {
        "臺北市":"63000",
        "新北市":"65000",
        "桃園市":"68000",
        "臺中市":"66000",
        "臺南市":"67000",
        "高雄市":"64000",
        "基隆市":"10017",
        "新竹市":"10018",
        "嘉義市":"10020",
        "新竹縣":"10004",
        "苗栗縣":"10005",
        "彰化縣":"10007",
        "南投縣":"10008",
        "雲林縣":"10009",
        "嘉義縣":"10010",
        "屏東縣":"10013",
        "宜蘭縣":"10002",
        "花蓮縣":"10015",
        "臺東縣":"10014",
        "澎湖縣":"10016",
        "金門縣":"09020",
        "連江縣":"09007"
    };

    /*
    ==================================================
    初始化 Leaflet 地圖
    ==================================================
    */
    // 定義地圖可顯示的最大範圍
    // 西南角:[緯度, 經度]
    // 東北角:[緯度, 經度]
    // 範圍包含:臺灣本島、澎湖、金門、連江(馬祖)
    const taiwanBounds = [
        [21, 118],
        [27, 123]
    ];

    // 建立 Leaflet 地圖
    const map = L.map("map", {
        // 限制地圖拖曳範圍
        maxBounds: taiwanBounds,
        // 1.0 表示完全不可拖曳超出範圍
        maxBoundsViscosity: 1.5,
        // 最小縮放層級
        // 7 剛好可完整看到金門、連江及臺灣
        minZoom: 7,
        // 最大縮放層級
        maxZoom: 10
    }).setView([24, 121], 7);

    L.tileLayer(
        "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
        {
            maxZoom: 18,
            attribution: "&copy; OpenStreetMap"
        }
    ).addTo(map);

    /*
    ==================================================
    建立圖例
    ==================================================
    */
    const legend =
        L.control({
            position: "bottomright"
        });

    legend.onAdd = function() {
        const div =
            L.DomUtil.create(
                "div",
                "legend"
            );

        div.innerHTML = `
            <div>
                <i style="background:#2e7d32;"></i>
                <span style="color:#000;">上班上課</span>
            </div>
            <div>
                <i style="background:#e63946;"></i>
                <span style="color:#000;">停班或停課</span>
            </div>
            <div>
                <i style="background:#f9c74f;"></i>
                <span style="color:#000;">其他資訊</span>
            </div>
            <div>
                <i style="background:#ccc;"></i>
                <span style="color:#000;">暫無公告</span>
            </div>
            <div>
                <i style="background:black;"></i>
                <span style="color:#000;">API 錯誤</span>
            </div>
        `;

        return div;
    };
    legend.addTo(map);

    /*
    ==================================================
    載入台灣縣市邊界
    ==================================================
    */
    fetch(
        "https://taiwan.md/assets/geo/taiwan-country.topo.json"
    ).then(res => res.json())
    .then(topo => {
        const geojson =
            topojson.feature(
                topo,
                topo.objects.map
            );
        geojsonLayer =
            L.geoJSON(
                geojson,
                {
                    style: styleByData,
                    /*
                    建立每個縣市互動
                    */
                    onEachFeature(feature, layer) {
                        const name = feature.properties.name;
                        const content = `<b style="color:#000;">${name}</b><br>載入中...`;
                        /*
                        滑鼠移入 Tooltip
                        */
                        layer.bindTooltip(
                            content,
                            {
                                sticky: true,
                                direction: "top"
                            }
                        );
                        /*
                        手機點擊 Popup
                        */
                        layer.bindPopup(content);
                        let clicked = false;
                        layer.on({
                            /*
                            滑鼠移入
                            只有未點擊時才顯示效果
                            */
                            mouseover(e) {
                                if(clicked)
                                    return;
                                e.target.setStyle({
                                    weight:3,
                                    color:"#000",
                                    fillOpacity:0.9
                                });
                            },
                            /*
                            滑鼠離開
                            */
                            mouseout(e) {
                                if(clicked)
                                    return;
                                geojsonLayer.resetStyle(
                                    e.target
                                );
                            },
                            /*
                            點擊後鎖定 Popup
                            */
                            click(e) {
                                const county = e.target.feature.properties.name;
                                clicked = true;
                                // 關閉其他 Tooltip
                                geojsonLayer.eachLayer(layer=>{layer.closeTooltip();});
                                map.fitBounds(e.target.getBounds());

                                // 載入有公告鄉鎮
                                loadTownLayer(county);

                                showPopup(
                                    e.target,
                                    e.latlng
                                );
                            }
                        });
                    }
                }
            )
            .addTo(map);
        loadData();
    })
    .catch(err => {
        console.error(
            "地圖載入失敗",
            err
        );
        showStatus(
            "地圖資料載入失敗"
        );
    });

    /*
    ==================================================
    狀態顏色設定
    ==================================================
    */
    // 狀態代號對應實際顏色
    const colorMap = {
        green: "#2e7d32",  // 上班上課
        red: "#e63946",    // 停班或停課
        yellow: "#f9c74f", // 其他資訊
        gray: "#ccc",      // 暫無公告
        black: "#000"      // API錯誤
    };

    /*
    ==================================================
    狀態判斷字典,使用正則表達式
    ==================================================
    */
    const statusRegex = {
        // 停班或停課
        red: [
            // 已達停止標準
            /已達.*停.*(班|課)/,

            // 停止上班 / 停止上課
            /停止上班/,
            /停止上課/,

            // 停班停課
            /停班/,
            /停課/,

            // 停上班 / 停上課
            /停上班/,
            /停上課/
        ],

        // 上班上課
        green: [
            // 正常 / 照常
            /正常上班/,
            /正常上課/,
            /照常上班/,
            /照常上課/,

            // 同時出現上班與上課
            /上班.*上課/
        ]
    };

    /*
    ==================================================
    依公告內容判斷縣市狀態
    ==================================================
    */
    function getStatusColor(name) {
        // API 錯誤
        if(errorFlag) {
            return "black";
        }

        // 取得該縣市公告
        const summary = data?.areas?.[name]?.summary || [];

        // 暫無公告
        if(summary.length === 0 || summary.includes("暫無公告 (No announcements)")) {
            return "gray";
        }

        // 外部 API 錯誤
        if(summary.length === 0 || summary.includes("無法取得資訊 (Unable to fetch data)")) {
            return "black";
        }

        /*
        ----------------------------------------------
        判斷是否包含 "縣市名稱:"
        例如:
        金門縣:
        花蓮縣:
        ----------------------------------------------
        */
        // 去除前字串
        const cleanSummary =
            summary.map(line =>
                String(line)
                    .trim()
                    .replace(
                        /^\[\d+\/\d+\]\s*/,
                        ""
                    )
            );
        // 尋找"縣市"總公告
        const regionRegex = new RegExp(`^${name}:`);
        const targetLines = cleanSummary.filter(line => regionRegex.test(line));
        if(targetLines.length === 0) {
            return "yellow";
        }

        /*
        ----------------------------------------------
        逐行分析公告
        ----------------------------------------------
        */
        for(const line of targetLines) {
            // 先處理未達停止
            if(/未達.*停.*(班|課)/.test(line)){
                return "green";
            }

            // 再判斷停班停課
            for(const regex of statusRegex.red){
                if(regex.test(line)){
                    return "red";
                }
            }

            // 最後判斷正常
            for(const regex of statusRegex.green){
                if(regex.test(line)){
                    return "green";
                }
            }
        }

        /*
        ----------------------------------------------
        其他未分類資訊
        ----------------------------------------------
        */
        return "yellow";
    }

    /*
    ==================================================
    依資料設定縣市顏色
    ==================================================
    */
    function styleByData(feature) {

        const name =
            feature.properties.name;


        const status =
            getStatusColor(name);


        return {
            fillColor: colorMap[status],
            color:"#000000",
            weight:1.5,
            fillOpacity:
                status === "gray"
                ? 0.7
                : 0.8
        };
    }

    /*
    ==================================================
    取得有公告的鄉鎮名稱 函數
    例如:「高雄市那瑪夏區」回傳「那瑪夏區」
    ==================================================
    */
    function getTownAnnouncements(county){
        const summary = data?.areas?.[county]?.summary || [];
        return summary
            .map(line =>
                String(line)
                    .trim()
                    .replace(/^\[[^\]]+\]\s*/, "")
            )
            .filter(line =>
                line.startsWith(county) &&
                !line.startsWith(`${county}:`)
            )
            .map(line => ({
                county: county,
                town: line.substring(county.length).split(":")[0]
            }));
    }

    /*
    ==================================================
    鄉鎮顏色
    ==================================================
    */
    function getTownStatusColor(county, town){
        const summary = data?.areas?.[county]?.summary || [];
        const key = county + town + ":";
        const lines = summary.filter(line => line.includes(key) );

        if(lines.length===0) return "gray";

        // 優先檢查「未達停止」否定條件
        for(const line of lines){
            if(/未達.*停.*(班|課)/.test(line)) return "green";
            for(const regex of statusRegex.red){
                if(regex.test(line)) return "red";
            }
        }
        // 其次檢查正常條件
        for(const line of lines){
            for(const regex of statusRegex.green){
                if(regex.test(line)) return "green";
            }
        }
        return "yellow";
    }

    /*
    ==================================================
    載入指定縣市的鄉鎮圖層 (僅包含有公告的鄉鎮)
    ==================================================
    */
    async function loadTownLayer(county){
        const code = countyCode[county];
        if(!code) return;
        const townNames = getTownAnnouncements(county).map(item => item.town);
        if(townNames.length === 0) return;
        // 使用 taiwan.md 官方 TopoJSON 路徑 (需允許 CORS)
        const url = `/country%20and%20town%20shape/towns-${code}.json`;
        const res = await fetch(url);
        if(!res.ok){
            console.error("載入鄉鎮資料錯誤:", res.status, url);
            return;
        }
        const topo = await res.json();
        const geojson = topojson.feature(topo, topo.objects.map);
        // 篩選有公告的鄉鎮
        const features = geojson.features.filter(f=> townNames.includes(f.properties.name));
        if(features.length === 0) return;
        const filtered = { type:"FeatureCollection", features: features };
        // 建立或加入圖層
        if(!townLayer){
            townLayer = L.geoJSON(filtered, {
                style: feature => styleTownByData(feature, county),
                onEachFeature(feature, layer){
                    layer.county = county;
                    setupTownLayer(layer, county);
                }
            }).addTo(map);
            townLayer.bringToFront();
        } else {
            L.geoJSON(filtered, {
                style: feature => styleTownByData(feature, county),

                onEachFeature(feature, layer){
                    layer.county = county;
                    setupTownLayer(layer, county);
                }
            }).eachLayer(layer=>{
                townLayer.addLayer(layer);
            });
        }
    }

    function setupTownLayer(layer, county){
        const townName = layer.feature.properties.name;
        const lines = data.areas[county].summary
            .map(line =>
                String(line)
                    .trim()
                    .replace(county, "")
            )
            .filter(line =>
                line.includes(townName + ":")
            );
        const content =`<b style="color:#000;">${county} ${townName}</b><hr>${lines.join("<br>")}`;
        layer.bindTooltip(
            content,
            {
                sticky:true,
                direction:"top"
            }
        );
        layer.bindPopup(content);
        layer.on("click", function(e){
            const center = layer.getBounds().getCenter();

            map.flyTo(center, 11);

            layer.openPopup(center);
        });
    }

    /*
    ==================================================
    設定鄉鎮樣式
    ==================================================
    */
    function styleTownByData(feature, county){
        const town = feature.properties.name;
        const status = getTownStatusColor(county, town);
        return {
            fillColor: colorMap[status],
            color:"#333",
            weight:1,
            opacity:0.3,
            fillOpacity:0.8
        };
    }

    /*
    ==================================================
    讀取資料
    ==================================================
    */
    async function loadData(){
        const today = new Date().toLocaleDateString("zh-TW", {timeZone:"Asia/Taipei"});
        try{
            const cache = localStorage.getItem(cacheKey);
            if(cache){
                const cacheObj = JSON.parse(cache);
                if(cacheObj.cacheDate === today){
                    data = cacheObj.data;
                    updateMap();
                    showStatus("使用今日快取資料");
                    // 載入所有有公告的鄉鎮
                    for(const county of Object.keys(data.areas)){
                        const names = getTownAnnouncements(county).map(item => item.town);
                        if(names.length > 0){
                            await loadTownLayer(county);
                        }
                    }

                    // 更新公告 alerts"
                    renderAlerts("alerts");

                    return;
                }
            }
            // 資料過期或不存在,重新抓取
            await updateDataFromAPI();
            // 資料更新完成後載入鄉鎮
            for(const county of Object.keys(data.areas)){
                const names = getTownAnnouncements(county).map(item => item.town);
                if(names.length > 0){
                    await loadTownLayer(county);
                }
            }

            // 更新公告 alerts"
            renderAlerts("alerts");
        }
        catch(err){
            console.error(err);
            errorFlag = true;
            updateMap();
        }
    }

    /*
    ==================================================
    取得 API
    ==================================================
    */
    async function updateDataFromAPI() {
        setLoading(true);
        try {
            const res = await fetch(apiUrl);
            if(!res.ok) {
                throw new Error(
                    res.status
                );
            }

            data = await res.json();
            const today = new Date()
                .toLocaleDateString(
                    "zh-TW",
                    {
                        timeZone:"Asia/Taipei"
                    }
                );

            localStorage.setItem(
                cacheKey,
                JSON.stringify({
                    cacheDate:today,
                    data:data
                })
            );

            errorFlag = false;
            updateMap();
            showStatus("資料更新完成");
        }

        catch(err) {
            console.error(
                "workschoolclose API 錯誤",
                err
            );
            errorFlag = true;
            showStatus("無法取得資料");
            updateMap();
        }
        finally {
            setLoading(false);
        }
    }

    /*
    ==================================================
    更新地圖內容
    ==================================================
    */
    function updateMap() {
        if(!geojsonLayer)
            return;
        geojsonLayer.eachLayer(layer => {
            const name = layer.feature.properties.name;
            let text;

            if(errorFlag) {
                text = "無法取得資訊 (Unable to fetch data)";
            }
            else {
                const summary = data?.areas?.[name]?.summary || [];
                text = summary.join("<br>");

                if(text === "") {
                    text = "暫無公告 (No announcements)";
                }
            }

            const content = `<b style="color:#000;">${name}</b><hr>${text}`;

            layer.setStyle(
                styleByData(
                    layer.feature
                )
            );

            // 更新 Popup
            layer.setPopupContent(
                content
            );

            // 更新 Tooltip
            if(layer.getTooltip()) {
                layer.setTooltipContent(
                    content
                );
            }
        });

        if(data?.feedUpdated) {
            document.getElementById("updated-time")
            .textContent = new Date(data.feedUpdated)
            .toLocaleString(
                "zh-TW",
                {
                    timeZone:
                        "Asia/Taipei",
                    hour12:false
                }
            );
        }

        if(townLayer){
            townLayer.eachLayer(layer=>{

                // 更新顏色
                layer.setStyle(
                    styleTownByData(
                        layer.feature,
                        layer.county
                    )
                );

                // 更新文字內容
                const county = layer.county;
                const townName = layer.feature.properties.name;

                const lines = data.areas[county].summary
                    .map(line =>
                        String(line)
                            .trim()
                            .replace(county, "")
                    )
                    .filter(line =>
                        line.includes(townName + ":")
                    );

                const content = `<b style="color:#000;">${county} ${townName}</b><hr>${lines.join("<br>")}`;

                // 更新 Popup
                layer.setPopupContent(content);

                // 更新 Tooltip
                if(layer.getTooltip()){
                    layer.setTooltipContent(content);
                }
            });
        }
    }

    /*
    ==================================================
    其他功能
    ==================================================
    */
    function showPopup(layer, latlng) {
        // 在滑鼠點擊的位置開啟 Popup
        layer.openPopup(latlng);
    }

    function showStatus(msg) {
        document
        .getElementById("status")
        .textContent = msg;
    }

    function setLoading(flag) {
        const btn =
            document.getElementById(
                "refresh"
            );

        btn.disabled = flag;
        btn.textContent =
            flag ?
            "更新中..." :
            "更新資訊";
    }

    /*
    ==================================================
    手動更新
    ==================================================
    */
    document
    .getElementById("refresh")
    .onclick = async function() {
        showStatus("正在更新資訊...");
        try {
            await updateDataFromAPI();
            showStatus("資料更新完成");
        } catch (err) {
            console.error(err);
            showStatus("資料更新失敗");
        }
    };

    /*
    ==================================================
    公告區塊
    ==================================================
    */
    
    function renderAlerts(divId){
        if(!data || !data.areas){
            console.error("沒有可用資料");
            return;
        }
        const alerts = [];

        // 取得所有縣市 alerts
        Object.values(data.areas).forEach(area => {
            if(!area.alerts) return;
            area.alerts.forEach(alert => {
                const summary = String(alert.summary || "").trim();
                // 排除無效資料
                if(
                    summary === "" ||
                    summary === "無法取得資訊 (Unable to fetch data)" ||
                    summary === "暫無公告 (No announcements)"
                ){
                    return;
                }
                alerts.push({
                    updated: alert.updated,
                    summary: summary
                });

            });

        });

        // 依更新時間排序,新資訊在前
        alerts.sort((a, b) =>
            new Date(b.updated) - new Date(a.updated)
        );
        const html = alerts.map(alert => {
            const time = new Date(alert.updated)
                .toLocaleString(
                    "zh-TW",
                    {
                        timeZone:"Asia/Taipei",
                        hour12:false
                    }
                );

            return `
                <div class="alert-item">
                    <b>[${time}] </b>${alert.summary}
                </div>
            `;
        }).join("");

        const div = document.getElementById(divId);
        if(div){
            div.innerHTML = html || "目前沒有公告";
        }
    }
</script>

<!-- 公告 -->
<div class="alerts-panel">
    <div id="alerts"></div>
</div>

結語

這次的小專案從發想到完成,前後僅花了約 3 天。回顧整個開發過程, AI 並非一次就能產出符合需求的成果,而是透過不斷地來回溝通與調整,才逐步完成最終版本。

我認為, Vibe Coding 並不是完全取代程式設計,而是改變了開發的方式。開發者可以將更多時間投入在需求分析、功能設計與使用者體驗,而將較為繁瑣的程式撰寫交由 AI 協助完成。即使不熟悉某種程式語言,也能透過反覆驗證與修正,完成一個可實際運作的專案。

當然, AI 所生成的程式碼仍然需要人工審查與測試,尤其是在效能、安全性及邏輯正確性方面,更不能完全依賴模型的輸出。不過,對於一般的小型專案、工具開發或原型設計而言, Vibe Coding 已經能大幅降低開發門檻,並有效提升開發效率。

未來,如果有一個想實作卻遲遲沒有開始的小點子,也不妨試著讓 AI 成為我們的開發夥伴。或許只需要幾天的時間,就能將原本停留在腦海中的想法,變成一個真正可以使用的作品。

參見

參考資料

  • vibe coding。(2026年7月9日)。維基百科,自由的百科全書。2026年7月13日參考自 https://zh.wikipedia.org/zh-tw/Vibe_coding
  • ithomemhjao(2021年6月28日)。《賴田捕手:番外篇》第 38 天:用 Netlify Functions 佈署 Line Bot。 iT 邦幫忙。2026年7月13日參考自 <https://ithelp.ithome.com.tw/articles/10257235
  • 開源地圖資料集 台灣的形狀 - SVG、GeoJSON、TopoJSON — 給開發者、設計師、研究者的完整開源地圖資料。(無日期)。 Taiwan.md 。2026年7月13日參考自 https://taiwan.md/taiwan-shape/
  • 各國颱風路徑。(無日期)。NCDR 天氣與氣候監測網。2026年7月13日參考自 https://watch.ncdr.nat.gov.tw/watch_typhoon
  • Windy。(無日期)。Windy: Weather forecast & weather radar 。2026年7月13日參考自 https://www.windy.com/