Contents

Vibe Coding Collaboration Project - Map of work and school closures in Taiwan

The cover image was generated by Google Gemini.

In 2026, with the rapid development of AI, Vibe Coding has become a commonly used approach for assisting software development.

Vibe Coding?

So, what exactly is Vibe Coding?

Simply put, Vibe Coding refers to a process in which humans describe the problems they want to solve or tasks they want to accomplish to large language models using natural language prompts, and the models then generate or modify code accordingly. In this way, even users without a professional programming background can utilize AI to create functional programs.

A Spontaneous Project Idea

Recently, as Typhoon Bavi approached Taiwan, discussions about whether to suspend work and classes due to the typhoon emerged across counties and cities. Regardless of whether work and classes were suspended, I wanted to quickly determine whether my location was affected by typhoon-related announcements.

However, I found that the information provided by the Directorate-General of Personnel Administration (DGPA) - Suspension of Work and Classes Due to Natural Disasters website was not sufficiently intuitive. When the amount of information increased, it was often difficult to quickly locate the county or city of interest. Therefore, I came up with the idea of transforming the text-based information into a visual map.

https://josh-test-lab.github.io/posts/Vibe%20Coding%20Collaboration%20Project/20260709_14.gif
The predicted path of Typhoon Bavi, from https://watch.ncdr.nat.gov.tw/watch_typhoon.

Although I am familiar with statistical programming languages such as R and Python, and have some basic knowledge of HTML syntax, writing JavaScript, which I had not deeply studied before, was still challenging.

Fortunately, AI has become sufficiently mature nowadays. Therefore, I decided to let AI handle the code generation for this small project, while I played the role of a “strategist”, responsible for defining requirements, reviewing code, conducting practical tests, and reporting missing functionalities so that AI could continuously refine the implementation.

Ultimately, the main functionality of the project was completed within only one day. Including subsequent feature adjustments, bug fixes, and updates, the entire process took approximately three days. Without AI assistance, simply searching for JavaScript syntax, learning related technologies, and locating appropriate data sources would likely have taken around two weeks to complete the project. This demonstrates that Vibe Coding can significantly shorten development time and effectively improve development efficiency.

Data Collection

https://josh-test-lab.github.io/posts/Vibe%20Coding%20Collaboration%20Project/open%20data.png
Open data of suspension of work and classes due to natural disasters.

First, I investigated the available data publication channels and discovered that the government already provides open data for Suspension of Work and Classes Due to Natural Disasters through the Government Open Data Platform.

Furthermore, according to the Open Government Data License 2.1:

The Data Providing Organization grants User a perpetual, worldwide, non-exclusive, irrevocable, royalty-free copyright license to reproduce, distribute, publicly transmit, publicly broadcast, publicly recite, publicly present, publicly perform, compile, adapt to the Open Data provided for any purpose, including but not limited to making all kinds of Derivative Works either as products or services. Therefore, the open data provided by the government can be legally reproduced, adapted, and publicly transmitted. Based on this dataset, I decided to transform the original text-based information into a visual map, making suspension-of-work-and-class information more intuitive and accessible.

https://josh-test-lab.github.io/posts/Vibe%20Coding%20Collaboration%20Project/open%20data%20license.en.png
Open Government Data License, version 1.0.

Vibe Coding

API Processing

This project utilized the free version of ChatGPT to assist with development. On one hand, I wanted to explore the current capabilities of OpenAI’s large language models; on the other hand, I also wanted to evaluate whether the free version was sufficient to support general users in developing small-scale projects.

First, to retrieve data from an RSS Feed and perform preliminary processing, I referred to the article 《賴田捕手:番外篇》第 38 天:用 Netlify Functions 佈署 Line Bot. I decided to utilize the serverless computing service provided by Netlify Functions to retrieve the RSS Feed of Suspension of Work and Classes Due to Natural Disasters https://alerts.ncdr.nat.gov.tw/RssAtomFeed.ashx?AlertType=33.

Next, Netlify Functions parsed, organized, and transformed the RSS data into the format required by the website, allowing the front-end application to directly access and utilize the processed data. The transformation process is summarized as follows:

  • Before processing
 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>
...
  • After processing
 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
}

As mentioned previously, I am not very familiar with JavaScript. Therefore, the code for this part of the project was mainly generated by ChatGPT, while I was responsible for defining requirements, reviewing the program logic, conducting practical tests, reporting issues, and continuously refining the implementation.

After multiple rounds of adjustments, feature additions, and debugging, the data processing workflow was successfully completed, and the API was successfully implemented. To reduce API response time and minimize unnecessary requests to the remote data source, I additionally designed a caching mechanism. Whenever the remote data remains unchanged, the API directly returns the existing cached data instead of retrieving and parsing the RSS Feed again, significantly improving overall performance.

The code is shown below:

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

Visualization

After completing the data processing, the next step was to implement the most important part of the project: visualization.

This part was also developed with the assistance of ChatGPT, which helped generate the HTML, JavaScript, and CSS code. The implementation was combined with the basemap provided by OpenStreetMap and the administrative boundary data of Taiwan provided by Taiwan.md. The map was then constructed to display the administrative regions of each county and city, with different colors representing their respective suspension-of-work-and-class statuses.

Each colored administrative region can be clicked to view the latest suspension announcements for that county or city.

In addition, an announcement panel was implemented to display notifications sorted by publication time, allowing users to quickly browse the latest information.

https://josh-test-lab.github.io/posts/Vibe%20Coding%20Collaboration%20Project/final%20work.en.png
Map of work and school closures in Taiwan.

The final result not only allows users to identify the suspension status of each county and city at a glance but also provides detailed information through interactive map elements and the announcement list.

The relevant HTML code is shown below:

   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
<!-- 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">
      Update Information
  </button>

  <span class="status" id="status">
      Loading...
  </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 = "https://yao-chih.netlify.app/api/workschoolclose";
    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;">Work and Classes as Usual</span>
            </div>
            <div>
                <i style="background:#e63946;"></i>
                <span style="color:#000;">Work or Classes Suspended</span>
            </div>
            <div>
                <i style="background:#f9c74f;"></i>
                <span style="color:#000;">Other Information</span>
            </div>
            <div>
                <i style="background:#ccc;"></i>
                <span style="color:#000;">No Announcement</span>
            </div>
            <div>
                <i style="background:black;"></i>
                <span style="color:#000;">API Error</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(
            "Failed to load map.",
            err
        );
        showStatus(
            "Failed to load map data."
        );
    });

    /*
    ==================================================
    狀態顏色設定
    ==================================================
    */
    // 狀態代號對應實際顏色
    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("Error loading township data: ", 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("Using cached data from today");
                    // 載入所有有公告的鄉鎮
                    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("Data update completed");
        }

        catch(err) {
            console.error(
                "workschoolclose API error",
                err
            );
            errorFlag = true;
            showStatus("Unable to retrieve data");
            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 ?
            "Updating..." :
            "Update Information";
    }

    /*
    ==================================================
    手動更新
    ==================================================
    */
    document
    .getElementById("refresh")
    .onclick = async function() {
        showStatus("Updating information...");
        try {
            await updateDataFromAPI();
            showStatus("Data update completed");
        } catch (err) {
            console.error(err);
            showStatus("Data update failed");
        }
    };

    /*
    ==================================================
    公告區塊
    ==================================================
    */
    
    function renderAlerts(divId){
        if(!data || !data.areas){
            console.error("No available data");
            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 || "No announcements available at this time";
        }
    }
</script>

<div class="alerts-panel">
    <div id="alerts"></div>
</div>

Conclusion

This small project took approximately three days from the initial idea to completion. Looking back on the entire development process, AI was not able to produce a perfect solution that fully met the requirements in a single attempt. Instead, the final version was gradually achieved through continuous communication, adjustments, and refinements.

In my opinion, Vibe Coding does not aim to completely replace programming; rather, it changes the way software is developed. Developers can spend more time focusing on requirement analysis, feature design, and user experience, while delegating more repetitive coding tasks to AI. Even without being familiar with a specific programming language, it is still possible to create a practical and functional project through continuous verification and refinement.

Of course, AI-generated code still requires human review and testing, especially regarding performance, security, and logical correctness. Nevertheless, for small projects, tool development, and prototyping, Vibe Coding has already significantly lowered the barrier to entry for software development and effectively improved development efficiency.

In the future, if there is a small idea that you have wanted to implement but have not yet started, consider allowing AI to become your development partner. Perhaps in just a few days, an idea that once existed only in your mind can become a real and usable project.

See Also

References