diff --git a/AGENTS.md b/AGENTS.md index e1ea709..ad08ee0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -98,6 +98,26 @@ python -m http.server 8090 # เปิด http://localhost:8090/ui/index. จะ render หน้าใหม่ให้อัตโนมัติ (ฟัง event `langchange`) - **ชื่อเฉพาะ (ชื่อสถานี/จังหวัด/สายรถ) ไม่ต้องแปล** — คงภาษาไทย +## ข้อมูลเส้นทางจาก GIS (QGIS → GeoJSON → แผนที่) + +- **ห้ามแก้ `resource/data/geojson-web/*.geojson` ด้วยมือ** — เป็นไฟล์ที่ "สร้าง" จาก shapefile ใน + `resource/data/QGIS Project/*.shp` (ตารางจับคู่ `SHP_MAP` อยู่ในสคริปต์) — user แก้ใน QGIS แล้วกด Save +- แปลง/อัปเดตด้วยคำสั่งเดียว (ไม่ใช่ build step ของเว็บ — รันมือเมื่อข้อมูลเส้นเปลี่ยน): + ```bash + python resource/tools/qgis-to-web.py --check # ตรวจก่อน (ไม่เขียนไฟล์) — "เหมือนเดิม ✓" = ไม่มีอะไรเปลี่ยน + python resource/tools/qgis-to-web.py # เขียนจริง (--from geojson = ทางเดิมผ่าน GeoJSON-2/) + python resource/tools/qgis-to-web.py --list # ดูตารางรหัสสาย ↔ ไฟล์ .shp + ``` +- สคริปต์จะ**ปฏิเสธ**ไฟล์ที่ CRS ไม่ใช่ WGS84 (พิกัดเป็น UTM) และตัดจุดที่หลุดกรอบประเทศไทย +- **ตรวจสุขภาพข้อมูลก่อนใช้**: `python resource/tools/audit-geojson.py` (CRS · พิกัดว่าง/ซ้ำ · + ช่วงเส้นตัดตรง · ปลายเส้นตรงจุดจอดไหม · ไฟล์ซ้ำ/ไม่ถูกใช้) +- กติกา + ตารางเลเยอร์↔รหัสสาย + วิธี export: `resource/data/QGIS Project/GeoJSON-2/README.md` +- แผนที่ใช้ Leaflet (vendor ใน `ui/vendor/leaflet/`) — **ห้ามให้ CSS ภายนอกกำหนด width/height ของ + `svg.leaflet-zoom-animated`** (จะถูกยุบเป็น 0×0 แล้ว "เส้นทางไม่แสดง" — มี guard ใน `ui/map.css` แล้ว) +- ตรวจว่าเส้นทางแสดงจริง ต้องวัด `getBoundingClientRect()` เทียบกับกล่องแผนที่ — นับ `` ใน DOM ไม่พอ + +> 📌 กติกาจุดขึ้นรถประจำทางอื่นๆ (`8 other_stop.json`): ดู **`resource/data/8 other_stop.md`** — ระบุสายที่ **ห้ามเพิ่ม** entry และรายการที่ห้ามลบ + ## ลำดับการอ่านไฟล์เมื่อเริ่มงาน 1. `AGENTS.md` (ไฟล์นี้) → `DESIGN.md` (ถ้าแตะ UI) @@ -109,3 +129,178 @@ python -m http.server 8090 # เปิด http://localhost:8090/ui/index. - commit ล่าสุดเน้น: sponsor marquee (เลื่อนสปอนเซอร์), ลบไฟล์ backup HTML - `.gitignore` ว่างเปล่า — ถ้าเพิ่มไฟล์ขยะ (เช่น .DS_Store) ให้เพิ่มใน .gitignore - งานถัดไปที่คาดว่าเกี่ยวข้อง: นำดีไซน์นี้ไป implement ใน `web-at-transit` (Next.js) + +## หน้ารายละเอียดป้าย `#/stops/<รหัสป้าย>` — ข้อมูลมาจากไหน + +หน้า `ui/partials/stopDetail.html` เป็น "โครงเปล่า" ล้วน ๆ (มีแต่ ` + + +
+

แก้ไข schedules.json เครื่องมือภายใน · ไม่ได้เป็นส่วนของเว็บ

+
+ กำลังโหลด… +
+ + + + + + + +
+ +
+ + +
+
+ +
+

ผลตรวจทั้งไฟล์

+

ตัวเลข/รูปแบบเวลา · จุดจอดที่ไม่ตรงกับลำดับสาย · จำนวนเที่ยวไม่เท่ากันข้ามจุดในทิศเดียวกัน

+
+
+ +
+
วางไฟล์ schedules.json ที่นี่เพื่อเปิด
+ + + + + diff --git a/resource/data/schedules.json b/resource/data/schedules.json index efa20de..e7dae15 100644 --- a/resource/data/schedules.json +++ b/resource/data/schedules.json @@ -1,244 +1,106 @@ { - "schedules": [ + "schema": 2, + "index": true, + "note": "สารบัญชี้ไป scheduleslist/schedules.json (1 ไฟล์ = 1 เส้นทาง) — แก้ไฟล์ย่อยนั้นโดยตรง หรือใช้ resource/data/schedules-editor.html", + "dir": "scheduleslist/", + "routes": [ { - "schedule_id": 1, "route_id": "101", - "station_id": 3, - "direction_note": null, - "departure_times": ["06:30", "07:20", "08:10", "09:00", "09:50", "10:40", "11:30", "12:20", "13:10", "14:00", "14:50", "15:40", "16:30", "17:30"], - "schedule_note": null + "file": "schedules101.json", + "n_directions": 4, + "n_stops": 8, + "n_trips": 64 }, { - "schedule_id": 2, - "route_id": "101", - "station_id": 1, - "direction_note": null, - "departure_times": ["07:30", "08:20", "09:10", "10:00", "10:50", "11:50", "13:00", "14:00", "15:00"], - "schedule_note": null - }, - { - "schedule_id": 3, - "route_id": "101", - "station_id": 2, - "direction_note": "ไปอ่างทอง", - "departure_times": ["07:30", "08:20", "09:10", "10:00", "10:50", "11:40", "12:30", "13:20", "14:10", "15:00", "15:50", "16:40", "17:30", "18:30"], - "schedule_note": null - }, - { - "schedule_id": 4, - "route_id": "101", - "station_id": 2, - "direction_note": "ไปอยุธยา", - "departure_times": ["08:00", "08:50", "09:40", "10:30", "11:20", "12:20", "13:30", "14:30", "15:30"], - "schedule_note": "เวลารถเปลี่ยนทุกวัน โดยเฉพาะวันหยุด" - }, - { - "schedule_id": 5, "route_id": "15", - "station_id": 1, - "direction_note": null, - "departure_times": ["05:00", "05:45", "06:30", "07:30"], - "schedule_note": null + "file": "schedules15.json", + "n_directions": 3, + "n_stops": 4, + "n_trips": 22 }, { - "schedule_id": 6, - "route_id": "15", - "station_id": 2, - "direction_note": null, - "departure_times": ["05:30", "06:20", "07:05", "07:55", "08:40", "09:30", "11:20", "12:10", "13:00", "15:00"], - "schedule_note": null - }, - { - "schedule_id": 7, - "route_id": "15", - "station_id": 6, - "direction_note": null, - "departure_times": ["06:00", "08:30", "09:15", "10:00", "12:30", "14:00", "15:00", "16:00"], - "schedule_note": "เวลารถเปลี่ยนทุกวัน" - }, - { - "schedule_id": 8, "route_id": "902", - "station_id": 1, - "direction_note": null, - "departure_times": ["04:00", "04:30", "05:00", "05:30", "06:00", "06:30", "07:00", "07:30", "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30"], - "schedule_note": null + "file": "schedules902.json", + "n_directions": 2, + "n_stops": 2, + "n_trips": 53 }, { - "schedule_id": 9, - "route_id": "902", - "station_id": 6, - "direction_note": null, - "departure_times": ["06:00", "06:30", "07:00", "07:30", "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00"], - "schedule_note": null - }, - { - "schedule_id": 10, "route_id": "951", - "station_id": 9, - "direction_note": null, - "departure_times": ["04:00", "04:20", "04:40", "05:00", "05:20", "05:40", "06:00", "06:20", "06:40", "07:00", "07:20", "07:40", "08:00", "08:20", "08:40", "09:00", "09:20", "09:40", "10:00", "10:20", "10:40", "11:00", "11:20", "11:40", "12:00", "12:20", "12:40", "13:00", "13:20", "13:40", "14:00", "14:20", "14:40", "15:00", "15:20", "15:40", "16:00", "16:20", "16:40", "17:00", "17:20", "17:40", "18:00"], - "schedule_note": null + "file": "schedules951.json", + "n_directions": 2, + "n_stops": 6, + "n_trips": 47 }, { - "schedule_id": 11, "route_id": "952", - "station_id": 8, - "direction_note": "จากตลาดวิเศษ", - "departure_times": ["04:30", "10:00", "15:00"], - "schedule_note": null + "file": "schedules952.json", + "n_directions": 2, + "n_stops": 2, + "n_trips": 6 }, { - "schedule_id": 12, - "route_id": "952", - "station_id": 12, - "direction_note": null, - "departure_times": ["07:00", "10:30", "15:00"], - "schedule_note": "10:30 และ 7:00 มีเฉพาะวันหยุด" - }, - { - "schedule_id": 13, "route_id": "954", - "station_id": 8, - "direction_note": "จากท่าช้าง", - "departure_times": ["08:00"], - "schedule_note": "เวลาเปลี่ยนทุกวัน" + "file": "schedules954.json", + "n_directions": 1, + "n_stops": 1, + "n_trips": 4 }, { - "schedule_id": 14, "route_id": "8", - "station_id": 13, - "direction_note": null, - "departure_times": ["03:30", "04:00", "04:30", "05:00", "05:30", "06:00", "06:30", "07:00", "07:30", "08:00", "08:30", "09:00", "09:30", "11:00", "12:00", "13:00", "14:00", "15:00", "17:00"], - "schedule_note": null + "file": "schedules8.json", + "n_directions": 2, + "n_stops": 2, + "n_trips": 4 }, { - "schedule_id": 15, - "route_id": "8", - "station_id": 8, - "direction_note": "จากโพธิ์ทอง", - "departure_times": ["05:00", "05:30", "06:00", "06:30", "07:00", "07:30", "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "12:30", "13:30", "14:30", "15:30", "16:30", "18:30"], - "schedule_note": "เวลาเปลี่ยนทุกวัน" - }, - { - "schedule_id": 16, "route_id": "464", - "station_id": 9, - "direction_note": null, - "departure_times": ["04:40", "05:10", "05:40", "06:10", "06:40", "07:10", "07:40", "08:15", "08:50", "09:25", "10:00", "10:35", "11:10", "11:45", "12:20", "12:55", "13:30", "14:05", "14:40", "15:15", "15:50", "16:25", "17:00", "17:40"], - "schedule_note": null + "file": "schedules464.json", + "n_directions": 3, + "n_stops": 4, + "n_trips": 88 }, { - "schedule_id": 17, - "route_id": "464", - "station_id": 10, - "direction_note": null, - "departure_times": ["05:00", "05:40", "06:20", "07:10", "08:00", "08:40", "09:20", "10:00", "10:40", "11:20", "12:00", "12:40", "13:20", "14:00", "14:40", "15:20", "16:00", "16:40", "17:20", "18:00"], - "schedule_note": null - }, - { - "schedule_id": 18, - "route_id": "464", - "station_id": 1, - "direction_note": "ไปสุพรรณบุรี", - "departure_times": ["06:30", "07:10", "07:50", "08:40", "09:30", "10:10", "10:50", "11:30", "12:10", "12:50", "13:30", "14:10", "14:50", "15:30", "16:10", "16:50", "17:30", "18:10", "18:50", "19:30"], - "schedule_note": null - }, - { - "schedule_id": 19, - "route_id": "464", - "station_id": 1, - "direction_note": "ไปสระบุรี", - "departure_times": ["05:40", "06:10", "06:40", "07:10", "07:40", "08:10", "08:40", "09:15", "09:50", "10:25", "11:00", "11:35", "12:10", "12:45", "13:20", "13:55", "14:30", "15:05", "15:40", "16:15", "16:50", "17:25", "18:00", "18:40"], - "schedule_note": "เวลารถเปลี่ยนทุกวัน" - }, - { - "schedule_id": 20, "route_id": "641", - "station_id": 1, - "direction_note": null, - "departure_times": ["07:00", "08:00", "09:00", "10:00", "11:00", "12:00", "13:30", "14:30", "16:30"], - "schedule_note": null + "file": "schedules641.json", + "n_directions": 2, + "n_stops": 2, + "n_trips": 18 }, { - "schedule_id": 21, - "route_id": "641", - "station_id": 7, - "direction_note": null, - "departure_times": ["07:00", "08:00", "09:00", "10:00", "11:00", "12:00", "13:30", "14:30", "16:30"], - "schedule_note": "10:00 และ 13:30 ไม่ได้มีทุกวัน" - }, - { - "schedule_id": 22, "route_id": "2194", - "station_id": 8, - "direction_note": "จากวัดหัวเวียง", - "departure_times": ["05:00", "06:00", "07:00"], - "schedule_note": null + "file": "schedules2194.json", + "n_directions": 2, + "n_stops": 2, + "n_trips": 6 }, { - "schedule_id": 23, - "route_id": "2194", - "station_id": 4, - "direction_note": null, - "departure_times": ["16:00", "17:00", "18:00"], - "schedule_note": null - }, - { - "schedule_id": 24, "route_id": "324", - "station_id": 1, - "direction_note": null, - "departure_times": ["10:00"], - "schedule_note": null + "file": "schedules324.json", + "n_directions": 2, + "n_stops": 2, + "n_trips": 2 }, { - "schedule_id": 25, - "route_id": "324", - "station_id": 8, - "direction_note": "จากวัดไชโยวรวิหาร", - "departure_times": ["08:00"], - "schedule_note": null - }, - { - "schedule_id": 26, "route_id": "1011", - "station_id": 1, - "direction_note": null, - "departure_times": ["12:00", "16:00", "17:00"], - "schedule_note": null + "file": "schedules1011.json", + "n_directions": 2, + "n_stops": 2, + "n_trips": 6 }, { - "schedule_id": 27, - "route_id": "1011", - "station_id": 8, - "direction_note": "จากวัดสีบัวทอง", - "departure_times": ["06:00", "06:30", "14:30"], - "schedule_note": null - }, - { - "schedule_id": 28, "route_id": "2231", - "station_id": 1, - "direction_note": null, - "departure_times": ["16:00"], - "schedule_note": null + "file": "schedules2231.json", + "n_directions": 2, + "n_stops": 2, + "n_trips": 2 }, { - "schedule_id": 29, - "route_id": "2231", - "station_id": 8, - "direction_note": "จากวัดมหานาม", - "departure_times": ["08:00"], - "schedule_note": null - }, - { - "schedule_id": 30, "route_id": "999", - "station_id": 14, - "direction_note": null, - "departure_times": [], - "schedule_note": "ยังไม่มีข้อมูลตารางเวลา" + "file": "schedules999.json", + "n_directions": 1, + "n_stops": 1, + "n_trips": 0 } ] -} \ No newline at end of file +} diff --git a/resource/data/scheduleslist/schedules101.json b/resource/data/scheduleslist/schedules101.json new file mode 100644 index 0000000..c1edb39 --- /dev/null +++ b/resource/data/scheduleslist/schedules101.json @@ -0,0 +1,124 @@ +{ + "schema": 3, + "route_id": "101", + "route_name": "อ่างทอง-ป่าโมก-อยุธยา", + "station_order": [ + 1, + 2, + 3 + ], + "weekday": { + "label": "เวลาวันทำงาน", + "directions": { + "ออกจากอ่างทอง": { + "from_station_id": 1, + "departures": [ + "07:30", + "08:20", + "09:10", + "10:00", + "10:50", + "11:50", + "13:00", + "14:00", + "15:00" + ] + }, + "ออกจากอยุธยา": { + "from_station_id": 3, + "departures": [ + "07:30", + "08:20", + "09:10", + "10:00", + "10:50", + "11:40", + "12:30", + "13:20", + "14:10", + "15:00", + "15:50", + "16:40", + "17:30", + "18:30" + ] + }, + "ป่าโมกไปอ่างทอง": { + "from_station_id": 2, + "departures": [ + "08:00", + "08:50", + "09:40", + "10:30", + "11:20", + "12:20", + "13:30", + "14:30", + "15:30" + ] + }, + "ป่าโมกไปอยุธยา": { + "from_station_id": 2, + "departures": [ + "06:30", + "07:20", + "08:10", + "09:00", + "09:50", + "10:40", + "11:30", + "12:20", + "13:10", + "14:00", + "14:50", + "15:40", + "16:30", + "17:30" + ] + } + } + }, + "holiday": { + "label": "เวลาวันหยุด", + "directions": { + "ออกจากอ่างทอง": { + "from_station_id": 1, + "departures": [ + "09:30", + "10:30", + "12:00", + "14:30" + ] + }, + "ออกจากอยุธยา": { + "from_station_id": 3, + "departures": [ + "06:50", + "08:30", + "10:00", + "11:40", + "13:20", + "15:00", + "17:00" + ] + }, + "ป่าโมกไปอ่างทอง": { + "from_station_id": 2, + "departures": [ + "06:20", + "08:30" + ] + }, + "ป่าโมกไปอยุธยา": { + "from_station_id": 2, + "departures": [ + "07:40", + "09:20", + "10:50", + "12:30", + "13:20" + ] + } + } + } +} diff --git a/resource/data/scheduleslist/schedules1011.json b/resource/data/scheduleslist/schedules1011.json new file mode 100644 index 0000000..661c845 --- /dev/null +++ b/resource/data/scheduleslist/schedules1011.json @@ -0,0 +1,40 @@ +{ + "schema": 2, + "route_id": "1011", + "generated_from": "schedules.json", + "station_order": [ + 1, + 8 + ], + "directions": [ + { + "dir_id": "from-1", + "dir_label": null, + "stops": [ + { + "station_id": 1, + "times": [ + "12:00", + "16:00", + "17:00" + ] + } + ] + }, + { + "dir_id": "dir-1", + "dir_label": "จากวัดสีบัวทอง", + "stops": [ + { + "station_id": 8, + "times": [ + "06:00", + "06:30", + "14:30" + ], + "dir_note": "จากวัดสีบัวทอง" + } + ] + } + ] +} diff --git a/resource/data/scheduleslist/schedules15.json b/resource/data/scheduleslist/schedules15.json new file mode 100644 index 0000000..803bcce --- /dev/null +++ b/resource/data/scheduleslist/schedules15.json @@ -0,0 +1,79 @@ +{ + "schema": 2, + "route_id": "15", + "generated_from": "schedules.json", + "station_order": [ + 1, + 2, + 4, + 5, + 6 + ], + "directions": [ + { + "dir_id": "from-1", + "dir_label": null, + "stops": [ + { + "station_id": 1, + "times": [ + "05:00", + "05:45", + "06:30", + "07:30" + ] + } + ] + }, + { + "dir_id": "all", + "dir_label": null, + "stops": [ + { + "station_id": 2, + "times": [ + "05:30", + "06:20", + "07:05", + "07:55", + "08:40", + "09:30", + "11:20", + "12:10", + "13:00", + "15:00" + ] + }, + { + "station_id": 6, + "times": [ + "06:00", + "08:30", + "09:15", + "10:00", + "12:30", + "14:00", + "15:00", + "16:00" + ] + } + ] + }, + { + "dir_id": "new-3", + "dir_label": null, + "stops": [ + { + "station_id": 5, + "derive": { + "from_station_id": 6, + "offset_min": 30, + "note": "ท่ารถมินิบัสต่างจังหวัด" + }, + "times": [] + } + ], + "autoTimes": true + } + ] +} diff --git a/resource/data/scheduleslist/schedules2194.json b/resource/data/scheduleslist/schedules2194.json new file mode 100644 index 0000000..cadaa35 --- /dev/null +++ b/resource/data/scheduleslist/schedules2194.json @@ -0,0 +1,40 @@ +{ + "schema": 2, + "route_id": "2194", + "generated_from": "schedules.json", + "station_order": [ + 4, + 8 + ], + "directions": [ + { + "dir_id": "dir-1", + "dir_label": "จากวัดหัวเวียง", + "stops": [ + { + "station_id": 8, + "times": [ + "05:00", + "06:00", + "07:00" + ], + "dir_note": "จากวัดหัวเวียง" + } + ] + }, + { + "dir_id": "from-4", + "dir_label": null, + "stops": [ + { + "station_id": 4, + "times": [ + "16:00", + "17:00", + "18:00" + ] + } + ] + } + ] +} diff --git a/resource/data/scheduleslist/schedules2231.json b/resource/data/scheduleslist/schedules2231.json new file mode 100644 index 0000000..283d492 --- /dev/null +++ b/resource/data/scheduleslist/schedules2231.json @@ -0,0 +1,36 @@ +{ + "schema": 2, + "route_id": "2231", + "generated_from": "schedules.json", + "station_order": [ + 1, + 8 + ], + "directions": [ + { + "dir_id": "from-1", + "dir_label": null, + "stops": [ + { + "station_id": 1, + "times": [ + "16:00" + ] + } + ] + }, + { + "dir_id": "dir-1", + "dir_label": "จากวัดมหานาม", + "stops": [ + { + "station_id": 8, + "times": [ + "08:00" + ], + "dir_note": "จากวัดมหานาม" + } + ] + } + ] +} diff --git a/resource/data/scheduleslist/schedules324.json b/resource/data/scheduleslist/schedules324.json new file mode 100644 index 0000000..03d6364 --- /dev/null +++ b/resource/data/scheduleslist/schedules324.json @@ -0,0 +1,36 @@ +{ + "schema": 2, + "route_id": "324", + "generated_from": "schedules.json", + "station_order": [ + 1, + 8 + ], + "directions": [ + { + "dir_id": "from-1", + "dir_label": null, + "stops": [ + { + "station_id": 1, + "times": [ + "10:00" + ] + } + ] + }, + { + "dir_id": "dir-1", + "dir_label": "จากวัดไชโยวรวิหาร", + "stops": [ + { + "station_id": 8, + "times": [ + "08:00" + ], + "dir_note": "จากวัดไชโยวรวิหาร" + } + ] + } + ] +} diff --git a/resource/data/scheduleslist/schedules464.json b/resource/data/scheduleslist/schedules464.json new file mode 100644 index 0000000..1dce094 --- /dev/null +++ b/resource/data/scheduleslist/schedules464.json @@ -0,0 +1,141 @@ +{ + "schema": 2, + "route_id": "464", + "generated_from": "schedules.json", + "station_order": [ + 1, + 9, + 10 + ], + "directions": [ + { + "dir_id": "all", + "dir_label": null, + "stops": [ + { + "station_id": 9, + "times": [ + "04:40", + "05:10", + "05:40", + "06:10", + "06:40", + "07:10", + "07:40", + "08:15", + "08:50", + "09:25", + "10:00", + "10:35", + "11:10", + "11:45", + "12:20", + "12:55", + "13:30", + "14:05", + "14:40", + "15:15", + "15:50", + "16:25", + "17:00", + "17:40" + ] + }, + { + "station_id": 10, + "times": [ + "05:00", + "05:40", + "06:20", + "07:10", + "08:00", + "08:40", + "09:20", + "10:00", + "10:40", + "11:20", + "12:00", + "12:40", + "13:20", + "14:00", + "14:40", + "15:20", + "16:00", + "16:40", + "17:20", + "18:00" + ] + } + ] + }, + { + "dir_id": "dir-1", + "dir_label": "ไปสุพรรณบุรี", + "stops": [ + { + "station_id": 1, + "times": [ + "06:30", + "07:10", + "07:50", + "08:40", + "09:30", + "10:10", + "10:50", + "11:30", + "12:10", + "12:50", + "13:30", + "14:10", + "14:50", + "15:30", + "16:10", + "16:50", + "17:30", + "18:10", + "18:50", + "19:30" + ], + "dir_note": "ไปสุพรรณบุรี" + } + ] + }, + { + "dir_id": "dir-2", + "dir_label": "ไปสระบุรี", + "stops": [ + { + "station_id": 1, + "times": [ + "05:40", + "06:10", + "06:40", + "07:10", + "07:40", + "08:10", + "08:40", + "09:15", + "09:50", + "10:25", + "11:00", + "11:35", + "12:10", + "12:45", + "13:20", + "13:55", + "14:30", + "15:05", + "15:40", + "16:15", + "16:50", + "17:25", + "18:00", + "18:40" + ], + "dir_note": "ไปสระบุรี", + "note": null + } + ] + } + ] +} diff --git a/resource/data/scheduleslist/schedules641.json b/resource/data/scheduleslist/schedules641.json new file mode 100644 index 0000000..e6235de --- /dev/null +++ b/resource/data/scheduleslist/schedules641.json @@ -0,0 +1,53 @@ +{ + "schema": 2, + "route_id": "641", + "generated_from": "schedules.json", + "station_order": [ + 1, + 7, + 8 + ], + "directions": [ + { + "dir_id": "from-1", + "dir_label": null, + "stops": [ + { + "station_id": 1, + "times": [ + "07:00", + "08:00", + "09:00", + "10:00", + "11:00", + "12:00", + "13:30", + "14:30", + "16:30" + ] + } + ] + }, + { + "dir_id": "all", + "dir_label": null, + "stops": [ + { + "station_id": 7, + "times": [ + "07:00", + "08:00", + "09:00", + "10:00", + "11:00", + "12:00", + "13:30", + "14:30", + "16:30" + ], + "note": "10:00 และ 13:30 ไม่ได้มีทุกวัน" + } + ] + } + ] +} diff --git a/resource/data/scheduleslist/schedules8.json b/resource/data/scheduleslist/schedules8.json new file mode 100644 index 0000000..63ee335 --- /dev/null +++ b/resource/data/scheduleslist/schedules8.json @@ -0,0 +1,88 @@ +{ + "schema": 2, + "route_id": "8", + "generated_from": "schedules.json", + "station_order": [ + 13, + 8, + 6, + 5 + + ], + "directions": [ + { + "dir_id": "all", + "dir_label": null, + "stops": [ + { + "station_id": 13, + "times": [ + "07:30", + "10:00" + ] + } + ], + "speedKmh": 60 + }, + { + "dir_id": "dir-1", + "dir_label": null, + "stops": [ + { + "station_id": 6, + "times": [ + "10:00", + "13:00" + ], + "dir_note": null, + "note": null + } + ] + }, + { + "dir_id": "rungsit", + "dir_label": "ตลาดแสวงหา", + "stops": [ + { + "station_id": 8, + "derive": { + "from_station_id": 13, + "offset_min": 90, + "note": null + }, + "times": [] + } + ] + }, + { + "dir_id": "rungsit", + "dir_label": "ตลาดสดเทศบาลตำบลโพธิ์ทอง", + "stops": [ + { + "station_id": 8, + "derive": { + "from_station_id": 13, + "offset_min": 110, + "note": null + }, + "times": [] + } + ] + }, + { + "dir_id": "rungsit", + "dir_label": null, + "stops": [ + { + "station_id": 5, + "derive": { + "from_station_id": 6, + "offset_min": 30, + "note": null + }, + "times": [] + } + ] + } + ] +} diff --git a/resource/data/scheduleslist/schedules902.json b/resource/data/scheduleslist/schedules902.json new file mode 100644 index 0000000..16c45c7 --- /dev/null +++ b/resource/data/scheduleslist/schedules902.json @@ -0,0 +1,102 @@ +{ + "schema": 2, + "route_id": "902", + "generated_from": "schedules.json", + "station_order": [ + 1, + 15, + 6 + ], + "directions": [ + { + "dir_id": "from-1", + "dir_label": null, + "stops": [ + { + "station_id": 1, + "times": [ + "04:00", + "04:30", + "05:00", + "05:30", + "06:00", + "06:30", + "07:00", + "07:30", + "08:00", + "08:30", + "09:00", + "09:30", + "10:00", + "10:30", + "11:00", + "11:30", + "12:00", + "12:30", + "13:00", + "13:30", + "14:00", + "14:30", + "15:00", + "15:30", + "16:00", + "16:30", + "17:00", + "17:30" + ] + } + ] + }, + { + "dir_id": "rungsit", + "dir_label": null, + "stops": [ + { + "station_id": 15, + "derive": { + "from_station_id": 6, + "offset_min": 30, + "note": "รอรถที่ 7-11 หน้ากินซ่า (รถจากจตุจักรผ่านมาถึง)" + }, + "times": [] + } + ] + }, + { + "dir_id": "all", + "dir_label": null, + "stops": [ + { + "station_id": 6, + "times": [ + "06:00", + "06:30", + "07:00", + "07:30", + "08:00", + "08:30", + "09:00", + "09:30", + "10:00", + "10:30", + "11:00", + "11:30", + "12:00", + "12:30", + "13:00", + "13:30", + "14:00", + "14:30", + "15:00", + "15:30", + "16:00", + "16:30", + "17:00", + "17:30", + "18:00" + ] + } + ] + } + ] +} diff --git a/resource/data/scheduleslist/schedules951.json b/resource/data/scheduleslist/schedules951.json new file mode 100644 index 0000000..045f5a1 --- /dev/null +++ b/resource/data/scheduleslist/schedules951.json @@ -0,0 +1,147 @@ +{ + "schema": 2, + "route_id": "951", + "generated_from": "schedules.json", + "station_order": [ + 9, + 5, + 6, + 8 + ], + "directions": [ + { + "dir_id": "from-9", + "dir_label": null, + "stops": [ + { + "station_id": 9, + "times": [ + "04:00", + "04:20", + "04:40", + "05:00", + "05:20", + "05:40", + "06:00", + "06:20", + "06:40", + "07:00", + "07:20", + "07:40", + "08:00", + "08:20", + "08:40", + "09:00", + "09:20", + "09:40", + "10:00", + "10:20", + "10:40", + "11:00", + "11:20", + "11:40", + "12:00", + "12:20", + "12:40", + "13:00", + "13:20", + "13:40", + "14:00", + "14:20", + "14:40", + "15:00", + "15:20", + "15:40", + "16:00", + "16:20", + "16:40", + "17:00", + "17:20", + "17:40", + "18:00" + ] + }, + { + "station_id": 8, + "times": [], + "dir_note": "ตลาดวิเศษชัยชาญ", + "note": "ตลาดวิเศษชัยชาญ" + }, + { + "station_id": 8, + "times": [], + "dir_note": "ตลาดอ่างทอง", + "note": "ตลาดอ่างทอง" + } + ] + }, + { + "dir_id": "new-2", + "dir_label": null, + "stops": [ + { + "station_id": 6, + "times": [ + "04:20", + "04:40", + "05:00", + "05:20", + "05:40", + "06:00", + "06:20", + "06:40", + "07:00", + "07:20", + "07:40", + "08:00", + "08:20", + "08:40", + "09:00", + "09:20", + "09:40", + "10:00", + "10:20", + "10:40", + "11:00", + "11:20", + "11:40", + "12:00", + "12:20", + "12:40", + "13:00", + "13:20", + "13:40", + "14:00", + "14:20", + "14:40", + "15:00", + "15:20", + "15:40", + "16:00", + "16:20", + "16:40", + "17:00", + "17:20", + "17:40", + "18:00", + "18:20", + "18:40" + ] + }, + { + "station_id": 5, + "derive": { + "from_station_id": 6, + "offset_min": 30, + "note": "ท่ารถตู้ต่างจังหวัด รังสิต (รถจากจตุจักรผ่านมาถึง)" + }, + "times": [] + }, + { + "station_id": 9, + "times": [] + } + ] + } + ] +} diff --git a/resource/data/scheduleslist/schedules952.json b/resource/data/scheduleslist/schedules952.json new file mode 100644 index 0000000..587e84b --- /dev/null +++ b/resource/data/scheduleslist/schedules952.json @@ -0,0 +1,42 @@ +{ + "schema": 2, + "route_id": "952", + "generated_from": "schedules.json", + "station_order": [ + 11, + 12 + ], + "directions": [ + { + "dir_id": "dir-1", + "dir_label": "จากตลาดวิเศษ", + "stops": [ + { + "station_id": 11, + "times": [ + "04:30", + "10:00", + "15:00" + ], + "dir_note": "จากตลาดวิเศษ", + "note": "10:00 มีเฉพาะวันหยุด" + } + ] + }, + { + "dir_id": "all", + "dir_label": null, + "stops": [ + { + "station_id": 12, + "times": [ + "07:00", + "10:30", + "15:00" + ], + "note": " 7:00 มีเฉพาะวันหยุด" + } + ] + } + ] +} diff --git a/resource/data/scheduleslist/schedules954.json b/resource/data/scheduleslist/schedules954.json new file mode 100644 index 0000000..f5a5929 --- /dev/null +++ b/resource/data/scheduleslist/schedules954.json @@ -0,0 +1,68 @@ +{ + "schema": 2, + "route_id": "954", + "generated_from": "schedules.json", + "station_order": [ + 8, + 5, + 6 + ], + "directions": [ + { + "dir_id": "dir-1", + "dir_label": "จากตลาดท่าช้าง", + "stops": [ + { + "station_id": 8, + "times": [ + "03:30", + "05:10", + "10:20", + "12:40" + ], + "dir_note": "จากตลาดท่าช้าง" + }, + { + "station_id": 6, + "times": [ + "07:00", + "09:00", + "14:00", + "16:00" + ], + "dir_note": null + } + ] + }, + { + "dir_id": "rungsit", + "dir_label": null, + "stops": [ + { + "station_id": 5, + "derive": { + "from_station_id": 6, + "offset_min": 30, + "note": "" + }, + "times": [] + } + ] + }, + { + "dir_id": "rungsit", + "dir_label": "ตลาดสามโก้", + "stops": [ + { + "station_id": 8, + "derive": { + "from_station_id": 8, + "offset_min": 45, + "note": "จากตลาดสามโก้" + }, + "times": [] + } + ] + } + ] +} diff --git a/resource/data/scheduleslist/schedules999.json b/resource/data/scheduleslist/schedules999.json new file mode 100644 index 0000000..af7e007 --- /dev/null +++ b/resource/data/scheduleslist/schedules999.json @@ -0,0 +1,21 @@ +{ + "schema": 2, + "route_id": "999", + "generated_from": "schedules.json", + "station_order": [ + 14 + ], + "directions": [ + { + "dir_id": "from-14", + "dir_label": null, + "stops": [ + { + "station_id": 14, + "times": [], + "note": "ยังไม่มีข้อมูลตารางเวลา" + } + ] + } + ] +} diff --git a/resource/data/stations.json b/resource/data/stations.json index 1ee94e7..45bb0fc 100644 --- a/resource/data/stations.json +++ b/resource/data/stations.json @@ -8,7 +8,7 @@ "province_th": "อ่างทอง", "station_type": "main_terminal", "latitude": 14.594892813219857, - "longitude":100.45160878714961 + "longitude": 100.45160878714961 }, { "station_id": 2, @@ -16,9 +16,9 @@ "station_name_th": "สถานีขนส่งป่าโมก", "city_th": "ป่าโมก", "province_th": "อ่างทอง", - "station_type": "main_terminal", - "latitude": 14.494620342173755, - "longitude":100.44663039105356 + "station_type": "local_terminal", + "latitude": 14.494620342173755, + "longitude": 100.44663039105356 }, { "station_id": 3, @@ -27,8 +27,8 @@ "city_th": "พระนครศรีอยุธยา", "province_th": "อยุธยา", "station_type": "local_stop", - "latitude": 14.359304063054642, - "longitude":100.57729051741023 + "latitude": 14.359304063054642, + "longitude": 100.57729051741023 }, { "station_id": 4, @@ -37,8 +37,8 @@ "city_th": "พระนครศรีอยุธยา", "province_th": "อยุธยา", "station_type": "market", - "latitude": 14.358600551289177, - "longitude":100.57740172977549 + "latitude": 14.358600551289177, + "longitude": 100.57740172977549 }, { "station_id": 5, @@ -46,9 +46,9 @@ "station_name_th": "ท่ารถตู้ต่างจังหวัด รังสิต", "city_th": "รังสิต", "province_th": "ปทุมธานี", - "station_type": "van_terminal", - "latitude": 13.989149716177037, - "longitude":100.61472107391762 + "station_type": "main_terminal", + "latitude": 13.989149716177037, + "longitude": 100.61472107391762 }, { "station_id": 6, @@ -56,9 +56,9 @@ "station_name_th": "สถานีเดินรถโดยสารขนาดเล็ก (จตุจักร) รถตู้/มินิบัส", "city_th": "จตุจักร", "province_th": "กรุงเทพมหานคร", - "station_type": "van_terminal", - "latitude": 13.811802065338766, - "longitude":100.5498111488118 + "station_type": "main_terminal", + "latitude": 13.811802065338766, + "longitude": 100.5498111488118 }, { "station_id": 7, @@ -67,8 +67,8 @@ "city_th": "เมืองลพบุรี", "province_th": "ลพบุรี", "station_type": "main_terminal", - "latitude": 14.798689894136096, - "longitude":100.63316793418102 + "latitude": 14.798689894136096, + "longitude": 100.63316793418102 }, { "station_id": 8, @@ -85,8 +85,8 @@ "city_th": "เมืองสุพรรณบุรี", "province_th": "สุพรรณบุรี", "station_type": "main_terminal", - "latitude": 14.473737243267138, - "longitude":100.12544591300441 + "latitude": 14.473737243267138, + "longitude": 100.12544591300441 }, { "station_id": 10, @@ -95,8 +95,8 @@ "city_th": "เมืองสระบุรี", "province_th": "สระบุรี", "station_type": "main_terminal", - "latitude": 14.523709233795955, - "longitude":100.91901540002084 + "latitude": 14.523709233795955, + "longitude": 100.91901540002084 }, { "station_id": 11, @@ -105,8 +105,8 @@ "city_th": "วิเศษชัยชาญ", "province_th": "อ่างทอง", "station_type": "private_stop", - "latitude": 14.59666118926178, - "longitude":100.35213848667698 + "latitude": 14.59666118926178, + "longitude": 100.35213848667698 }, { "station_id": 12, @@ -114,9 +114,9 @@ "station_name_th": "สายใต้เก่า ปิ่นเกล้า จุดจอดรถตู้", "city_th": "บางกอกน้อย", "province_th": "กรุงเทพมหานคร", - "station_type": "van_terminal", - "latitude": 13.786761431062317, - "longitude":100.46776017448384 + "station_type": "main_terminal", + "latitude": 13.786761431062317, + "longitude": 100.46776017448384 }, { "station_id": 13, @@ -125,8 +125,8 @@ "city_th": "เมืองชัยนาท", "province_th": "ชัยนาท", "station_type": "main_terminal", - "latitude": 15.197359140046297, - "longitude":100.1245558104688 + "latitude": 15.197359140046297, + "longitude": 100.1245558104688 }, { "station_id": 14, @@ -135,58 +135,18 @@ "city_th": "เมืองอ่างทอง", "province_th": "อ่างทอง", "station_type": "main_terminal", - "latitude": 14.580083239362345, - "longitude":100.4841456500421 + "latitude": 14.580083239362345, + "longitude": 100.4841456500421 }, { "station_id": 15, - "station_code": "chaiyo_terminal", - "station_name_th": "สถานีขนส่งไชโย", - "city_th": "ไชโย", - "province_th": "อ่างทอง", - "station_type": "main_terminal" - }, - { - "station_id": 16, - "station_code": "pho_thong_terminal", - "station_name_th": "สถานีขนส่งโพธิ์ทอง", - "city_th": "โพธิ์ทอง", - "province_th": "อ่างทอง", - "station_type": "main_terminal" - }, - { - "station_id": 17, - "station_code": "sawaeng_ha_terminal", - "station_name_th": "สถานีขนส่งแสวงหา", - "city_th": "แสวงหา", - "province_th": "อ่างทอง", - "station_type": "main_terminal" - }, - { - "station_id": 18, - "station_code": "wiset_chai_chan_terminal", - "station_name_th": "สถานีขนส่งวิเศษชัยชาญ", - "city_th": "วิเศษชัยชาญ", - "province_th": "อ่างทอง", - "station_type": "main_terminal" - }, - { - "station_id": 19, - "station_code": "samko_terminal", - "station_name_th": "สถานีขนส่งสามโก้", - "city_th": "สามโก้", - "province_th": "อ่างทอง", - "station_type": "main_terminal" - }, - { - "station_id": 20, - "station_code": "at_market", - "station_name_th": "ตลาดอ่างทอง", - "city_th": "เมืองอ่างทอง", - "province_th": "อ่างทอง", + "station_code": "7-11 kinsa", + "station_name_th": "7-11 สาขากินซ่า", + "city_th": "รังสิต", + "province_th": "ปทุมธานี", "station_type": "main_terminal", - "latitude": 14.59372148660796, - "longitude":100.45079590645398 + "latitude": 13.9906952188289, + "longitude": 100.61469598208095 } ] -} +} \ No newline at end of file diff --git a/resource/data/stop-km.json b/resource/data/stop-km.json new file mode 100644 index 0000000..666287c --- /dev/null +++ b/resource/data/stop-km.json @@ -0,0 +1,57 @@ +{ + "8": { + "13": 197.42, + "6": 0.01 + }, + "15": { + "1": 0.02, + "2": 14.32, + "6": 109.52 + }, + "101": { + "3": 39.76, + "1": 0.02, + "2": 14.39 + }, + "324": { + "1": 29.52, + "8": 9.76 + }, + "464": { + "9": 0.0, + "10": 103.15, + "1": 44.95 + }, + "641": { + "1": 0.0, + "7": 43.53 + }, + "902": { + "1": 0.0, + "6": 100.28, + "15": 77 + + }, + "951": { + "9": 0.0, + "20": 42.25 + }, + "952": { + "12": 129.46 + }, + "954": { + "8": 0.0 + }, + "1011": { + "1": 36.02, + "8": 0.36 + }, + "2194": { + "8": 1.11, + "4": 40.84 + }, + "2231": { + "1": 0.0, + "8": 20.13 + } +} diff --git a/resource/tools/__pycache__/audit-geojson.cpython-311.pyc b/resource/tools/__pycache__/audit-geojson.cpython-311.pyc new file mode 100644 index 0000000..e9563ef Binary files /dev/null and b/resource/tools/__pycache__/audit-geojson.cpython-311.pyc differ diff --git a/resource/tools/__pycache__/qgis-to-web.cpython-311.pyc b/resource/tools/__pycache__/qgis-to-web.cpython-311.pyc new file mode 100644 index 0000000..4ac790f Binary files /dev/null and b/resource/tools/__pycache__/qgis-to-web.cpython-311.pyc differ diff --git a/resource/tools/__pycache__/schedules-to-grouped.cpython-311.pyc b/resource/tools/__pycache__/schedules-to-grouped.cpython-311.pyc new file mode 100644 index 0000000..0fb63a4 Binary files /dev/null and b/resource/tools/__pycache__/schedules-to-grouped.cpython-311.pyc differ diff --git a/resource/tools/__pycache__/stop-km.cpython-311.pyc b/resource/tools/__pycache__/stop-km.cpython-311.pyc new file mode 100644 index 0000000..f38d93f Binary files /dev/null and b/resource/tools/__pycache__/stop-km.cpython-311.pyc differ diff --git a/resource/tools/audit-geojson.py b/resource/tools/audit-geojson.py new file mode 100644 index 0000000..6f33445 --- /dev/null +++ b/resource/tools/audit-geojson.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""ตรวจสุขภาพข้อมูลเส้นทาง — QGIS → GeoJSON ที่เว็บใช้ + +รันจาก root ของโปรเจกต์: + python resource/tools/audit-geojson.py + +ตรวจ 3 ส่วน: + A. ไฟล์ส่งออกใน QGIS Project (GeoJSON-2/3/4) — CRS · พิกัดว่าง/ซ้ำ/หลุดกรอบ · ความหยาบของเส้น + B. ข้อมูลที่เว็บใช้จริง (resource/data/geojson-web/) — สถิติ + "ปลายเส้นตรงกับจุดจอดไหม" + C. เทียบ shapefile (ต้นทาง QGIS) ↔ geojson-web (ว่าต้องรัน pipeline ไหม) +""" +import importlib.util +import json +import math +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +TOOL = Path(__file__).with_name("qgis-to-web.py") +QDIR = ROOT / "resource" / "data" / "QGIS Project" +WEB = ROOT / "resource" / "data" / "geojson-web" +DATA = ROOT / "resource" / "data" +BBOX = (97.0, 103.0, 12.0, 17.5) +JUMP_KM = 1.5 +END_TOL_KM = 1.0 + +# ยืมตัวอ่าน shapefile + ตารางจับคู่จาก pipeline (DRY) +_spec = importlib.util.spec_from_file_location("q2w", TOOL) +q2w = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(q2w) + +issues = [] +def note(level, msg): issues.append((level, msg)) + + +def hav(a, b): + R = 6371.0 + p1, p2 = math.radians(a[1]), math.radians(b[1]) + dp, dl = p2 - p1, math.radians(b[0] - a[0]) + h = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2 + return 2 * R * math.asin(math.sqrt(h)) + + +def read_features(p): + txt = p.read_text(encoding="utf-8", errors="replace") + try: + d = json.loads(txt) + feats = list(d.get("features") or []) + if d.get("type") == "Feature" and "geometry" in d: + feats.append(d) + return feats, ("FeatureCollection" if "features" in d else "Feature") + except json.JSONDecodeError: + return [json.loads(l) for l in txt.splitlines() if l.strip()], "GeoJSONLines" + + +def lines_of(geom): + if not geom: + return [] + t, cs = geom.get("type"), geom.get("coordinates") or [] + if t == "LineString": + return [cs] if cs else [] + if t == "MultiLineString": + return [l for l in cs if l] + return [] + + +def audit_file(p): + feats, kind = read_features(p) + lines, empty = [], 0 + for f in feats: + ls = lines_of(f.get("geometry")) + if not ls: + empty += 1 + continue + lines += ls + pts = [c for l in lines for c in l] + if not pts: + return {"kind": kind, "feats": len(feats), "empty_feats": empty, "pts": 0} + jumps = [hav(l[i - 1], l[i]) for l in lines for i in range(1, len(l)) if hav(l[i - 1], l[i]) > JUMP_KM] + return { + "kind": kind, "feats": len(feats), "empty_feats": empty, "lines": len(lines), "pts": len(pts), + "km": sum(hav(l[i - 1], l[i]) for l in lines for i in range(1, len(l))), + "jumps": jumps, "max_jump": max(jumps) if jumps else 0.0, + "dups": sum(1 for l in lines for i in range(1, len(l)) if l[i] == l[i - 1]), + "out_of_box": sum(1 for c in pts if not (BBOX[0] < c[0] < BBOX[1] and BBOX[2] < c[1] < BBOX[3])), + "utm": max(abs(min(c[0] for c in pts)), abs(max(c[0] for c in pts))) > 1000, + "lines_pts": lines, "first": lines[0][0], "last": lines[-1][-1], + } + + +def table_header(title): + print("\n" + "=" * 104) + print(title) + print("=" * 104) + + +def stops_for(rid, routes, stations, others): + out = [] + for sid in (routes.get(rid, {}).get("station_ids") or []): + s = stations.get(sid) + if s and s.get("latitude") not in (None, ""): + out.append((s["station_name_th"], float(s["longitude"]), float(s["latitude"]))) + for o in others.get(rid, []): + out.append((o["station_name_th"] + "*", float(o["longitude"]), float(o["latitude"]))) + return out + + +def main(): + routes = {str(r["route_id"]): r for r in json.loads((DATA / "routes.json").read_text(encoding="utf-8"))["routes"]} + stations = {s["station_id"]: s for s in json.loads((DATA / "stations.json").read_text(encoding="utf-8"))["stations"]} + others = {} + op = DATA / "8 other_stop.json" + if op.exists(): + for o in json.loads(op.read_text(encoding="utf-8")).get("other_stop", []): + others.setdefault(str(o["route_id"]), []).append(o) + + # ── A. ไฟล์ส่งออกใน QGIS Project ── + table_header("A. ไฟล์ส่งออกใน QGIS Project (ต้นฉบับ — ยังไม่ได้เข้าสู่เว็บจนกว่าจะรัน pipeline)") + print(f"\n{'ไฟล์':<34}{'แบบ':<16}{'feat':<6}{'ว่าง':<6}{'จุด':<7}{'กม.':<8}{'ตัดตรง':<8}{'สูงสุด':<8}{'ซ้ำ':<5}{'นอกกรอบ':<9}CRS") + print("-" * 104) + for p in sorted(x for x in QDIR.rglob("*") if x.suffix.lower() in (".geojson", ".json") and x.suffix.lower() != ".qmd"): + st = audit_file(p) + rel = str(p.relative_to(QDIR)) + if st["pts"] == 0: + print(f"{rel:<34}{st['kind']:<16}{st['feats']:<6}{st['empty_feats']:<6}{'0':<7}{'-':<8}{'-':<8}{'-':<8}{'-':<5}{'-':<9}⚠️ ไม่มีพิกัด") + continue + if st["utm"]: + note("ERROR", f"{rel}: พิกัดเป็น UTM — ต้องบันทึก/export ใหม่เป็น EPSG:4326") + if st["out_of_box"]: + note("WARN", f"{rel}: มี {st['out_of_box']} จุดหลุดกรอบประเทศไทย") + print(f"{rel:<34}{st['kind']:<16}{st['feats']:<6}{st['empty_feats']:<6}{st['pts']:<7}{st['km']:<8.1f}" + f"{len(st['jumps']):<8}{st['max_jump']:<8.1f}{st['dups']:<5}{st['out_of_box']:<9}{'UTM ❌' if st['utm'] else 'WGS84 ✓'}") + + # ── B. ข้อมูลที่เว็บใช้จริง ── + table_header("B. ข้อมูลที่เว็บใช้จริง (resource/data/geojson-web/) — ชุดที่แผนที่โหลด") + print(f"\n{'สาย':<8}{'feat':<6}{'จุด':<7}{'กม.':<8}{'ตัดตรง':<8}{'สูงสุด':<8}ปลายเส้น ↔ จุดจอด (ห่างเกิน {END_TOL_KM} กม. = ⚠️)") + print("-" * 104) + for p in sorted(WEB.glob("*.geojson")): + rid = p.stem + st = audit_file(p) + if st["pts"] == 0: + print(f"{rid:<8}⚠️ ไม่มีพิกัด") + continue + cands = stops_for(rid, routes, stations, others) + ends = "" + if cands: + da, na = min((hav(st["first"], [c[1], c[2]]), c[0]) for c in cands) + db, nb = min((hav(st["last"], [c[1], c[2]]), c[0]) for c in cands) + ends = f"เริ่ม {na[:18]} {da:.1f} กม.{'✓' if da <= END_TOL_KM else '⚠️'} · จบ {nb[:18]} {db:.1f} กม.{'✓' if db <= END_TOL_KM else '⚠️'}" + if da > END_TOL_KM: + note("WARN", f"สาย {rid}: จุดเริ่มเส้นห่างจุดจอดที่ใกล้สุด {da:.1f} กม. ({na})") + if db > END_TOL_KM: + note("WARN", f"สาย {rid}: จุดจบเส้นห่างจุดจอดที่ใกล้สุด {db:.1f} กม. ({nb})") + if st["max_jump"] > 10: + note("WARN", f"สาย {rid}: ช่วงตัดตรงยาวสุด {st['max_jump']:.1f} กม. (เส้นหยาบ/ไม่เกาะถนน)") + print(f"{rid:<8}{st['feats']:<6}{st['pts']:<7}{st['km']:<8.1f}{len(st['jumps']):<8}{st['max_jump']:<8.1f}{ends}") + + # ── C. sync shapefile ↔ geojson-web ── + table_header("C. ตรวจ sync: shapefile (QGIS) ↔ geojson-web (เว็บใช้)") + print(f"\n{'สาย':<8}{'shapefile':<40}{'shp: จุด/กม.':<18}{'web: จุด/กม.':<18}สถานะ") + print("-" * 104) + stale = [] + for rid in sorted(q2w.SHP_MAP): + shp = QDIR / f"{q2w.SHP_MAP[rid]}.shp" + web = WEB / f"{rid}.geojson" + if not shp.exists(): + print(f"{rid:<8}{q2w.SHP_MAP[rid][:38]:<40}{'—':<18}{'—':<18}⚠️ ไม่พบ shapefile (ชื่อเปลี่ยน?)") + note("WARN", f"สาย {rid}: ไม่พบ shapefile {shp.name} — ชื่ออาจเปลี่ยนใน QGIS") + continue + recs = q2w.read_shp(shp) + sl = [l for r in recs for l in r] + skm = sum(hav(l[i - 1], l[i]) for l in sl for i in range(1, len(l))) + sn = sum(len(l) for l in sl) + if web.exists(): + wst = audit_file(web) + wn, wkm = wst["pts"], wst["km"] + else: + wn, wkm = 0, 0.0 + same = abs(sn - wn) <= 5 and abs(skm - wkm) < 0.05 + state = "ตรงกัน ✓" if same else "⚠️ ต้องรัน qgis-to-web.py" + if not same: + stale.append(rid) + print(f"{rid:<8}{shp.stem[:38]:<40}{f'{sn} / {skm:.1f}':<18}{f'{wn} / {wkm:.1f}':<18}{state}") + if stale: + note("WARN", f"geojson-web ไม่ตรงกับ shapefile {len(stale)} สาย ({', '.join(stale)}) → รัน `python resource/tools/qgis-to-web.py`") + else: + print("\n→ geojson-web ตรงกับ shapefile ทุกสาย ✓") + + # ── ไฟล์ประกอบอื่น ── + csvs = [str(p.relative_to(QDIR)) for p in QDIR.rglob("*.csv")] + if csvs: + note("INFO", f"ไฟล์ .csv ในโฟลเดอร์ QGIS (น่าจะเป็นไฟล์ทดสอบ): {csvs}") + zips = [p.name for p in QDIR.glob("*.zip")] + if zips: + note("INFO", f"มี .zip สำเนาโฟลเดอร์: {zips}") + no_prj = [p.name for p in QDIR.glob("*.shp") if not p.with_suffix(".prj").exists()] + if no_prj: + note("WARN", f"shapefile ไม่มี .prj (CRS ไม่ทราบ): {no_prj}") + no_geom = sorted(set(routes) - {p.stem for p in WEB.glob("*.geojson")}) + unused = sorted({p.stem for p in WEB.glob("*.geojson")} - set(routes)) + if no_geom: + note("INFO", f"อยู่ใน routes.json แต่ไม่มี geometry: {no_geom}") + if unused: + note("INFO", f"มี geometry แต่ไม่อยู่ใน routes.json: {unused}") + + print("\n" + "=" * 104) + print(f"สรุปประเด็น: {len(issues)} ข้อ") + for level in ("ERROR", "WARN", "INFO"): + ls = [m for lv, m in issues if lv == level] + if ls: + print(f"\n[{level}] {len(ls)} ข้อ") + for m in ls: + print(" -", m) + print(f"\nเกณฑ์: CRS ต้อง WGS84 · ตัดตรง >{JUMP_KM} กม. = หยาบเกินไป · ปลายเส้นห่างจุดจอด >{END_TOL_KM} กม. = ไม่ตรง") + return 1 if any(lv == "ERROR" for lv, _ in issues) else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/resource/tools/derive-times.py b/resource/tools/derive-times.py new file mode 100644 index 0000000..50dd80e --- /dev/null +++ b/resource/tools/derive-times.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""derive-times.py — เติมกฎ "จุดนี้ = เวลาจุดอ้างอิง ± n นาที" ให้ไฟล์สาย (resource/data/scheduleslist/) + +แนวคิด: เขียนกฎครั้งเดียวเป็นตาราง (resource/data/derive-times.csv) แล้วรันสคริปต์นี้ + → เติมบล็อก "derive" ให้จุดเป้าหมาย + ลบเวลาที่คัดลอกมาทิ้ง (กันข้อมูลไม่ตรงกัน) + ไม่ต้องจดจำไวยากรณ์ JSON และไม่ต้องแก้ทีละสายด้วยมือ + +ตาราง (CSV, คั่นด้วยจุลภาค — บรรทัดขึ้นต้น # = ความเห็น): + route_id, station_id, from_station_id, offset_min, note + 902, 15, 6, 30, รอรถที่ 7-11 หน้ากินซ่า + +วิธีใช้: + python resource/tools/derive-times.py --check # ดูว่าจะเปลี่ยนอะไร (ไม่เขียนไฟล์) + python resource/tools/derive-times.py # เขียนจริง + python resource/tools/derive-times.py --audit # ตรวจกฎ vs ไฟล์ (ไม่เขียน) +""" +import argparse +import csv +import json +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DATA = ROOT / "resource" / "data" +SUB_DIR = DATA / "scheduleslist" +TABLE = DATA / "derive-times.csv" + + +def read_table(path=TABLE): + """อ่านตารางกฎ → [{route_id, station_id, from_station_id, offset_min, note}]""" + if not path.exists(): + return [] + rows = [] + with path.open(encoding="utf-8-sig") as f: + for line in f: + line = line.strip() + if not line or line.startswith("#"): + continue + parts = [x.strip() for x in line.split(",")] + if parts[0].lower() == "route_id": # หัวตาราง + continue + if len(parts) < 4: + continue + rows.append({ + "route_id": str(parts[0]), + "station_id": int(parts[1]), + "from_station_id": int(parts[2]), + "offset_min": int(parts[3]), + "note": (parts[4] if len(parts) > 4 else "").strip() or None, + }) + return rows + + +def sub_path(rid): + return SUB_DIR / f"schedules{rid}.json" + + +def load_sub(rid): + """คืน (ข้อมูล, ชนิดขึ้นบรรทัด) — อ่านเป็น bytes เพราะ Path.read_text() แปลง CRLF→LF ให้อัตโนมัติ + (ถ้าอ่านด้วย read_text() จะตรวจชนิดขึ้นบรรทัดผิด แล้วเขียนไฟล์เป็น LF ทั้งที่เดิม CRLF)""" + f = sub_path(rid) + if not f.exists(): + return None, None + raw = f.read_bytes() + eol = "\r\n" if b"\r\n" in raw else "\n" + return json.loads(raw.decode("utf-8")), eol + + +def all_times(sub, station_id): + """เวลาจริงของจุดนั้น (จากทุกทิศ)""" + for d in sub.get("directions", []): + for s in d.get("stops", []): + if int(s["station_id"]) == int(station_id) and (s.get("times") or []): + return s["times"], d.get("dir_id") + return [], None + + +def find_stop(sub, station_id): + """คืน (ทิศ, จุด) ของจุดเป้าหมาย""" + for d in sub.get("directions", []): + for s in d.get("stops", []): + if int(s["station_id"]) == int(station_id): + return d, s + return None, None + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--check", action="store_true", help="dry run — ไม่เขียนไฟล์") + ap.add_argument("--audit", action="store_true", help="ตรวจกฎกับไฟล์ (ไม่เขียน)") + args = ap.parse_args() + + rules = read_table() + if not rules: + print(f"ไม่พบกฎในตาราง {TABLE.relative_to(ROOT)} (หรือไฟล์ว่าง)") + return 0 + + print(f"กฎทั้งหมด: {len(rules)} ข้อ" + (" [--check = ไม่เขียนไฟล์]" if args.check else "")) + problems = 0 + for r in rules: + rid = r["route_id"] + sub, eol = load_sub(rid) + if sub is None: + print(f" ✗ {rid}: ไม่พบไฟล์ {sub_path(rid).name}") + problems += 1 + continue + src_times, src_dir = all_times(sub, r["from_station_id"]) + d, stop = find_stop(sub, r["station_id"]) + if stop is None: + print(f" ✗ {rid}: ไม่พบจุด {r['station_id']} ในไฟล์ (ต้องมีจุดก่อนจึงจะตั้งกฎได้)") + problems += 1 + continue + if not src_times: + print(f" ✗ {rid}: จุดอ้างอิง {r['from_station_id']} ยังไม่มีเวลาจริง — คำนวณไม่ได้") + problems += 1 + continue + + had = len(stop.get("times") or []) + want = {"from_station_id": r["from_station_id"], "offset_min": r["offset_min"]} + if r["note"]: + want["note"] = r["note"] + already = stop.get("derive") == want and not had + if args.audit: + ok = already + print(f" {'✓' if ok else '✗'} {rid} จุด {r['station_id']} ← จุด {r['from_station_id']} " + f"{r['offset_min']:+d} นาที (ต้นทางมี {len(src_times)} เที่ยว" + + (f" · ทิศ {src_dir}" if src_dir else "") + ")" + + ("" if ok else f" — ไฟล์ยังไม่ตรง (มี times {had} · derive={stop.get('derive')})")) + if not ok: + problems += 1 + continue + + if already: + print(f" = {rid} จุด {r['station_id']}: ตั้งกฎไว้แล้ว ({r['offset_min']:+d} นาที) — ข้าม") + continue + + print(f" → {rid} จุด {r['station_id']} ← จุด {r['from_station_id']} {r['offset_min']:+d} นาที" + + (f" · ลบเวลาที่คัดลอกมา {had} เที่ยว" if had else "")) + if not args.check: + stop["derive"] = want + if had: + stop.pop("times", None) # ไม่เก็บเวลาซ้ำ — ให้เว็บคำนวณเสมอ + stop["times"] = [] + txt = json.dumps(sub, ensure_ascii=False, indent=2) + if eol == "\r\n": + txt = txt.replace("\n", "\r\n") + sub_path(rid).write_text(txt + eol, encoding="utf-8", newline="") + + if args.audit: + print(f"\nผลตรวจ: {len(rules) - problems}/{len(rules)} ตรงกัน" + (f" · ไม่ตรง {problems}" if problems else " ✓")) + print("\n— จุดที่ 'เวลาซ้ำกับอีกจุดในสายเดียวกัน' แต่ยังไม่มีกฎ (น่าจะต้องตั้ง derive) —") + cands = 0 + for f in sorted(SUB_DIR.glob("schedules*.json")): + sub2, _ = load_sub(f.stem.replace("schedules", "")) + if not sub2: + continue + sig = {} + for d in sub2.get("directions", []): + for st in d.get("stops", []): + t = tuple(st.get("times") or []) + if t: + sig.setdefault(t, []).append((d.get("dir_id"), st["station_id"], st.get("derive"))) + for times, who in sig.items(): + if len(who) < 2: + continue + if any(w[2] for w in who): # มีกฎแล้วบางจุด → ถือว่าจัดการแล้ว + continue + cands += 1 + print(f" · {sub2.get('route_id')}: " + " = ".join(f"จุด {w[1]} (ทิศ {w[0]})" for w in who) + + f" · {len(times)} เที่ยวเท่ากันเป๊ะ → เลือกจุดอ้างอิง + ใส่ offset") + print(" (ไม่มี)" if not cands else f" รวม {cands} กลุ่ม") + else: + print(f"\n{'ตรวจแล้ว (ไม่เขียนไฟล์)' if args.check else 'เขียนไฟล์แล้ว'} · ปัญหา {problems} รายการ") + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/resource/tools/merge-schedules.py b/resource/tools/merge-schedules.py new file mode 100644 index 0000000..e72d0a3 --- /dev/null +++ b/resource/tools/merge-schedules.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""รวมไฟล์ย่อย resource/data/scheduleslist/schedules.json → schedules.json ไฟล์เดียว (schema 2) + +ใช้เมื่อ: ต้องการย้อนกลับไปใช้ไฟล์เดียว (เช่น ส่งต่อ/สำรอง หรือโปรแกรมอื่นต้องการไฟล์รวม) +รัน: python resource/tools/merge-schedules.py # เขียน schedules.json (สำรองไฟล์เดิมเป็น .bak ก่อน) + python resource/tools/merge-schedules.py --check # ดูผลก่อน ไม่เขียน +""" +import argparse +import json +import shutil +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DATA = ROOT / "resource" / "data" +LIST_DIR = DATA / "scheduleslist" + + +def jdump(o): + return json.dumps(o, ensure_ascii=False, indent=2).replace("\n", "\r\n") + "\r\n" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--check", action="store_true") + args = ap.parse_args() + + if not LIST_DIR.exists(): + print("ไม่พบโฟลเดอร์ scheduleslist/"); return 1 + files = sorted(LIST_DIR.glob("schedules*.json"), + key=lambda p: (len(p.stem.replace("schedules", "")), p.stem)) + if not files: + print("ไม่พบไฟล์ย่อยใน scheduleslist/"); return 1 + + routes, bad = [], [] + for f in files: + try: + d = json.loads(f.read_text(encoding="utf-8")) + except Exception as e: + bad.append((f.name, str(e)[:60])); continue + rid = d.get("route_id") + if rid is None: + rid = f.stem.replace("schedules", "") + routes.append({ + "route_id": rid, + "station_order": d.get("station_order", []), + "directions": d.get("directions", []), + }) + if bad: + print("ไฟล์ที่อ่านไม่ได้ (ข้าม):") + for n, e in bad: + print(f" {n}: {e}") + doc = {"schema": 2, "routes": routes} + + trips = sum(len(s.get("times") or []) for r in routes for d in r["directions"] for s in (d.get("stops") or [])) + stops = sum(len(d.get("stops") or []) for r in routes for d in r["directions"]) + dirs = sum(len(r["directions"]) for r in routes) + print(f"รวมได้ {len(routes)} สาย · {dirs} ทิศ · {stops} จุด · {trips} เที่ยว") + if args.check: + print("[--check] ไม่เขียนไฟล์"); return 0 + dst = DATA / "schedules.json" + if dst.exists(): + shutil.copy2(dst, DATA / "schedules.json.bak") + print("สำรองไฟล์เดิมเป็น schedules.json.bak แล้ว") + dst.write_text(jdump(doc), encoding="utf-8", newline="") + print("เขียน schedules.json (ไฟล์เดียว) แล้ว") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/resource/tools/qgis-to-web.py b/resource/tools/qgis-to-web.py new file mode 100644 index 0000000..4b33a1b --- /dev/null +++ b/resource/tools/qgis-to-web.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""QGIS → GeoJSON สำหรับเว็บ (resource/data/geojson-web/) + +*** ไม่ใช่ build step ของเว็บ *** — เว็บเป็น static (AGENTS.md ข้อ 1) + สคริปต์นี้เป็นเครื่องมือ "เตรียมข้อมูล" รันมือ หลังแก้เส้นทางใน QGIS + +แหล่งข้อมูล 2 ทาง (ค่าเริ่มต้น = shapefile เพราะวิธีทำงานจริงคือแก้ใน QGIS แล้วกด Save): + python resource/tools/qgis-to-web.py # อ่าน <รหัสสาย>.shp ตามตาราง SHP_MAP (แนะนำ) + python resource/tools/qgis-to-web.py --from geojson # อ่าน GeoJSON-2/*.geojson (เส้นทางเดิม) + +ธงอื่น: + --check ตรวจเทียบกับไฟล์ปัจจุบัน ไม่เขียนไฟล์ + --list แสดงตารางจับคู่รหัสสาย ↔ ไฟล์ + สถานะ + +กติกาที่บังคับ: + 1. CRS ต้องเป็น WGS84 (EPSG:4326) — .prj ต้องบอก WGS84 และพิกัดต้องไม่ใช่ UTM (หลักล้าน) + 2. จุดที่หลุดกรอบประเทศไทย (lng 97–103, lat 12–17.5) ถูกตัดออก + 3. ปัดพิกัดเหลือ 5 ตำแหน่ง (แม่นยำ ~1 ม. พอสำหรับแผนที่) + 4. 1 record ของ shapefile = 1 feature (MultiLineString) · properties = {"route_id": "<รหัส>"} +""" +import argparse +import json +import re +import struct +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +QDIR = ROOT / "resource" / "data" / "QGIS Project" +SRC_GEOJSON = QDIR / "GeoJSON-2" +DST = ROOT / "resource" / "data" / "geojson-web" +BBOX = (97.0, 103.0, 12.0, 17.5) # lng_min, lng_max, lat_min, lat_max + +# ── ตารางจับคู่ "รหัสสาย → ไฟล์ .shp ในโปรเจกต์ QGIS" ───────────────────────── +# โปรเจกต์มีหลายเวอร์ชันต่อสาย — ตารางนี้ระบุตัวที่ป้อนเว็บ (ตรวจด้วยจุดเริ่ม/จุดจบ +# ของเส้นว่าเข้าคู่กันแล้ว) ถ้ามีการเปลี่ยนชื่อไฟล์ใน QGIS ต้องแก้ที่ตารางนี้ +SHP_MAP = { + "8": "8 Bangkok-Chainat", + "15": "15 angthong-Bangkok-local", + "101": "101-Angthong-pamok-Ayuthaya", + "324": "324-Angthong-watpikungthong1", + "464": "464 -suphanburi-saraburi", + "641": "641-Angthong-lopburi1", + "902": "902", + "905": "905 bangkok-singburi", + "951": "951 Bangkok-wisead-suphanburi", + "952": "952 กรุงเทพ-วิเศษชัยชาญ", + "954": "954", + "1011": "1011", + "2194": "2194", + "2231": "2231", + "XXX1": "XXX อ่างทอง-วิเศษฯ", + "XXX2": "XXX ป่าโมก-ผักไห่", +} + + +# ── อ่าน shapefile (polyline = type 3, รองรับ multi-part / หลาย record) ── +def read_shp(path): + """คืน list ของ record; แต่ละ record = list ของเส้น; แต่ละเส้น = list ของ [lng, lat]""" + b = path.read_bytes() + if len(b) < 100: + return [] + recs, off = [], 100 + while off + 8 <= len(b): + _, clen = struct.unpack(">ii", b[off:off + 8]) + rec = b[off + 8:off + 8 + clen * 2] + off += 8 + clen * 2 + if len(rec) < 44 or struct.unpack("= 2: + kept.append([[round(float(c[0]), 5), round(float(c[1]), 5)] for c in good]) + else: + dropped += 1 + return kept, dropped + + +def looks_like_utm(lines): + xs = [c[0] for l in lines for c in l] or [0] + return max(abs(min(xs)), abs(max(xs))) > 1000 + + +def from_shp(route_id): + """คืน (features, รายงาน) จาก shapefile ตาม SHP_MAP""" + stem = SHP_MAP.get(route_id) + if not stem: + return None, ["ไม่มีในตาราง SHP_MAP — ข้าม"] + path = QDIR / f"{stem}.shp" + if not path.exists(): + return None, [f"ไม่พบไฟล์ {path.name} (ชื่อเปลี่ยน? แก้ SHP_MAP)"] + ok = prj_ok(path) + if ok is False: + return None, [f"CRS ของ {path.name} เป็น UTM — ต้องบันทึกใหม่เป็น EPSG:4326"] + recs = read_shp(path) + if not recs: + return None, ["shapefile ไม่มีเส้น (หรือพิกัดว่าง)"] + if looks_like_utm([l for r in recs for l in r]): + return None, ["พิกัดเป็น UTM (ไม่ใช่ WGS84) — บันทึกใหม่โดยตั้ง CRS = EPSG:4326"] + + feats, dropped, pts = [], 0, 0 + for rec in recs: + kept, d = clean_lines(rec) + dropped += d + if not kept: + continue + feats.append({"type": "Feature", "properties": {"route_id": route_id}, + "geometry": {"type": "MultiLineString", "coordinates": kept}}) + pts += sum(len(l) for l in kept) + if not feats: + return None, ["หลังกรองแล้วไม่มีเส้นเหลือ — ข้าม"] + notes = [f"ไม่มี .prj (ไม่ทราบ CRS — ตรวจด้วยกรอบประเทศไทย)" if ok is None else ""] + if dropped: + notes.append(f"ตัด {dropped} ช่วงที่สั้น/หลุดกรอบ") + return feats, [n for n in notes if n] + + +def from_geojson(route_id): + """คืน (features, รายงาน) จาก GeoJSON-2/<รหัส>.geojson (เส้นทางเดิม)""" + path = SRC_GEOJSON / f"{route_id}.geojson" + if not path.exists(): + return None, ["ไม่พบไฟล์ใน GeoJSON-2 — ข้าม"] + try: + data = json.loads(path.read_text(encoding="utf-8")) + except Exception as e: + return None, [f"อ่าน JSON ไม่ได้: {e}"] + + feats_in = data.get("features", []) + all_lines = [] + for f in feats_in: + g = f.get("geometry") or {} + cs = g.get("coordinates") or [] + all_lines += ([cs] if g.get("type") == "LineString" else cs) + if not all_lines: + return None, ["ไม่มีพิกัดในไฟล์ (coordinates ว่าง) — ข้าม"] + if looks_like_utm([l for l in all_lines if l]): + return None, ["พิกัดเป็น UTM (ไม่ใช่ WGS84) — export ใหม่โดยตั้ง CRS = EPSG:4326"] + + out, dropped = [], 0 + for f in feats_in: + g = f.get("geometry") or {} + gtype, src = g.get("type"), [] + cs = g.get("coordinates") or [] + src = [cs] if gtype == "LineString" else cs + if gtype not in ("LineString", "MultiLineString") or not src: + continue + kept, d = clean_lines(src) + dropped += d + if not kept: + continue + if gtype == "LineString" and len(kept) > 1: + gtype = "MultiLineString" + out.append({"type": "Feature", "properties": {"route_id": route_id}, + "geometry": {"type": gtype, "coordinates": kept[0] if gtype == "LineString" else kept}}) + if not out: + return None, ["หลังกรองแล้วไม่มีเส้นเหลือ — ข้าม"] + notes = [f"ตัด {dropped} ช่วงที่สั้น/หลุดกรอบ"] if dropped else [] + return out, notes + + +def targets(mode): + """รายการ route_id ที่จะสร้าง (จากตาราง SHP_MAP หรือไฟล์ GeoJSON-2)""" + if mode == "shp": + return sorted(SHP_MAP) + return sorted(p.stem for p in SRC_GEOJSON.glob("*.geojson")) + + +def main(): + ap = argparse.ArgumentParser(description="QGIS (shapefile/GeoJSON) → resource/data/geojson-web/") + ap.add_argument("--from", dest="src", choices=["shp", "geojson"], default="shp", + help="แหล่งข้อมูล (ค่าเริ่มต้น shp)") + ap.add_argument("--check", action="store_true", help="ตรวจอย่างเดียว ไม่เขียนไฟล์") + ap.add_argument("--list", action="store_true", help="แสดงตารางจับคู่ + สถานะไฟล์") + args = ap.parse_args() + + ids = targets(args.src) + if args.list: + print(f"{'สาย':<8}{'ไฟล์ต้นทาง':<46}{'มีไฟล์':<8}{'.prj':<14}ไฟล์เว็บปัจจุบัน") + for rid in ids: + stem = SHP_MAP.get(rid, "") + p = QDIR / f"{stem}.shp" + prj = "WGS84 ✓" if prj_ok(p) is True else ("UTM ❌" if prj_ok(p) is False else "ไม่มี") + web = DST / f"{rid}.geojson" + print(f"{rid:<8}{stem[:44]:<46}{'มี' if p.exists() else '❌ ไม่มี':<8}{prj:<14}{'มี' if web.exists() else '—'}") + return + + from_shp_source = args.src == "shp" + label = "shapefile (QGIS Project/*.shp)" if from_shp_source else "GeoJSON-2/*.geojson" + print(f"ต้นทาง : {label} ({len(ids)} สาย)") + print(f"ปลายทาง: {DST.relative_to(ROOT)}" + (" [--check: ไม่เขียนไฟล์]\n" if args.check else "\n")) + DST.mkdir(parents=True, exist_ok=True) + + print(f"{'สาย':<8}{'จุด':<7}{'ไฟล์เดิม':<10}สถานะ") + written = skipped = unchanged = 0 + for rid in ids: + rid = re.sub(r"[^0-9A-Za-z]", "", rid) or rid + feats, notes = (from_shp(rid) if from_shp_source else from_geojson(rid)) + if feats is None: + print(f"{rid:<8}{'-':<7}{'-':<10}ข้าม — {'; '.join(notes)}") + skipped += 1 + continue + + out = DST / f"{rid}.geojson" + had_old = out.exists() + old_kb = f"{out.stat().st_size // 1024}KB" if had_old else "-" + payload = json.dumps({"type": "FeatureCollection", "features": feats}, + ensure_ascii=False, separators=(",", ":")) + n = sum(len(l) for f in feats for l in + ([f["geometry"]["coordinates"]] if f["geometry"]["type"] == "LineString" else f["geometry"]["coordinates"])) + same = had_old and out.read_text(encoding="utf-8").strip() == payload.strip() + + if args.check: + state = "เหมือนเดิม ✓" if same else ("ต่างจากเดิม ⚠️" if had_old else "ไฟล์ใหม่") + print(f"{rid:<8}{n:<7}{old_kb:<10}{state}") + continue + if same: + print(f"{rid:<8}{n:<7}{old_kb:<10}ไม่เปลี่ยน — ข้ามการเขียน") + unchanged += 1 + continue + out.write_text(payload, encoding="utf-8") + written += 1 + print(f"{rid:<8}{n:<7}{old_kb:<10}เขียนแล้ว ({len(payload) // 1024}KB)" + + (f" — {'; '.join(notes)}" if notes else "")) + + print(f"\nสรุป: เขียน {written} · ไม่เปลี่ยน {unchanged} · ข้าม {skipped}" + + (" (โหมด --check)" if args.check else "")) + if not args.check and written: + print("ขั้นถัดไป: เปิดเว็บกด Ctrl+Shift+R (ไฟล์ .geojson เป็น network-first — ไม่ต้อง bump VERSION)") + + +if __name__ == "__main__": + main() diff --git a/resource/tools/schedules-to-grouped.py b/resource/tools/schedules-to-grouped.py new file mode 100644 index 0000000..be0318e --- /dev/null +++ b/resource/tools/schedules-to-grouped.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""schedules.json: แบบแบน (30 record) → แบบ 2 ชั้น routes[] → directions[] → stops[] + +*** ไม่ใช่ build step ของเว็บ *** — เครื่องมือเตรียมข้อมูล รันมือครั้งเดียว (รันซ้ำได้ ไม่ทำลายข้อมูล) + +แนวคิด "มัดรวมตามสาย → ซอยย่อยตามจุด": + routes[] หนึ่งรายการต่อสาย (ผูกกับ routes.json ด้วย route_id) + station_order[] ลำดับจุดจอดตามที่รถวิ่ง (ตรวจกับพิกัดจริงเทียบปลายเส้น geojson แล้ว) + directions[] แกนทิศ — สายที่รถแยกทาง/วิ่ง 2 ทาง จะมีหลายทิศ + stops[] จุดจอดในทิศนั้น + station_id + times[] เวลาออกของจุดนี้ + dir_note ถ้อยคำทิศเดิมจากเจ้าของข้อมูล (เก็บไว้ ไม่แปลง) + note เงื่อนไขเวลาเดิมจากเจ้าของข้อมูล (เก็บไว้ ไม่แปลง) + groups[] (อนาคต) ใช้เมื่อเวลาชุดเดียวกันแยกตามวัน เช่น 10:00 เฉพาะวันหยุด + +กติกาการแยกทิศ (ยึดข้อมูลจริง): + - "จุดแยกทิศ" = จุดที่มี record หลายทิศ = จุดที่รถแยกทาง (เช่น สาย 101 จุด 2 ป่าโมก มีทั้ง 'ไปอยุธยา'/'ไปออ่างทอง') + - record ที่ไม่ระบุทิศ → ใช้ทิศของจุดแยกทิศที่อยู่ก่อนหน้าในลำดับ (จุดที่รถผ่านมาก่อน) + - สายที่ไม่ระบุทิศเลย → ทิศเดียว dir_id = "all" + +หมายเหตุ: เลิกใช้ schedule_id (ไม่มีโค้ดไหนอ้างถึง) — กุญแจคือ route_id + dir_id + station_id +""" +import argparse +import json +import math +import sys +from collections import OrderedDict +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DATA = ROOT / "resource" / "data" +SRC = DATA / "schedules.json" +ALL = "__all__" # กุญแจทิศ "ไม่แยกทิศ" (ใช้สตริงธรรมดา กันอักขระพิเศษ) + + +# ── เรขาคณิตเล็ก ๆ (ใช้ตรวจลำดับจุดจอดกับปลายเส้น) ── +def _hav(a, b): + R = 6371.0 + p1, p2 = math.radians(a[1]), math.radians(b[1]) + dp, dl = p2 - p1, math.radians(b[0] - a[0]) + h = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2 + return 2 * R * math.asin(math.sqrt(h)) + + +def stop_point(sid, stations): + st = stations.get(sid) + if not st: + return None + lat, lng = st.get("latitude"), st.get("longitude") + if lat in (None, "") or lng in (None, ""): + return None + try: + return (float(lng), float(lat)) + except (TypeError, ValueError): + return None + + +def geo_ends(rid): + """ปลายทั้งสองของเส้น (จุดแรก, จุดสุดท้าย) จาก geojson-web""" + p = DATA / "geojson-web" / f"{rid}.geojson" + if not p.exists(): + return None + g = json.loads(p.read_text(encoding="utf-8")) + segs = [] + for f in g.get("features", []): + cs = f["geometry"]["coordinates"] + segs += [cs] if f["geometry"]["type"] == "LineString" else cs + segs = [s for s in segs if s] + if not segs: + return None + return segs[0][0], segs[-1][-1] + + +def orient_order(rid, order, stations): + """คืน station_order ที่ตรงกับทิศที่รถวิ่งจริง (เทียบพิกัดกับปลายเส้น) + ธงว่าสลับหรือไม่""" + if len(order) < 2: + return list(order), False + ends = geo_ends(rid) + if not ends: + return list(order), False + a, b = ends + pf, pl = stop_point(order[0], stations), stop_point(order[-1], stations) + if not (pf and pl): + return list(order), False + same = _hav(pf, a) + _hav(pl, b) + swap = _hav(pf, b) + _hav(pl, a) + if swap < same: + return list(reversed(order)), True + return list(order), False + + +# ── การแยกทิศ (ไม่เดา — ใช้ "ทิศทางที่ระบุ" (direction_note) และ "จุดต้นทาง" เท่านั้น) ── +def direction_of(rec, first_station): + """ทิศของ record ตามข้อมูลที่ระบุไว้จริง + - มี direction_note → ทิศนั้น (แยกเป็น directions[] ของตัวเอง) + - ไม่มี note + เป็นจุดต้นทาง (station_order[0]) → 'ออกจากต้นทาง' (dir_id = from-) + - ไม่มี note + จุดอื่น → ทิศทางเดียว (dir_id = "all") + ไม่พยายามเดาว่าจุดปลายทางอยู่ขาไหน (ข้อมูลเดิมขัดกันเอง — ต้องให้เจ้าของข้อมูลยืนยัน) + """ + label = rec.get("direction_note") + if label: + return ("label", label) + if rec["station_id"] == first_station: + return ("start", rec["station_id"]) + return ("all", None) + + +def main(): + ap = argparse.ArgumentParser(description="schedules.json: แบน → 2 ชั้น (routes → directions → stops)") + ap.add_argument("--check", action="store_true", help="แสดงผลลัพธ์ ไม่เขียนไฟล์") + ap.add_argument("--out", default=str(SRC), help="ไฟล์ปลายทาง (ค่าเริ่มต้น: ทับ schedules.json)") + args = ap.parse_args() + + doc = json.loads(SRC.read_text(encoding="utf-8")) + if doc.get("schema") == 2: + print("ไฟล์เป็น schema 2 อยู่แล้ว — ไม่ต้องแปลง (รัน --force ไม่มี — แก้มือถ้าต้องการแปลงใหม่)") + return 0 + records = doc.get("schedules") or [] + routes = {str(r["route_id"]): r for r in json.loads((DATA / "routes.json").read_text(encoding="utf-8"))["routes"]} + stations = {x["station_id"]: x for x in json.loads((DATA / "stations.json").read_text(encoding="utf-8"))["stations"]} + + by_route = OrderedDict() + for rec in records: + by_route.setdefault(str(rec["route_id"]), []).append(rec) + + out_routes, warnings = [], [] + n_dup = 0 + for rid, recs in by_route.items(): + raw_order = routes.get(rid, {}).get("station_ids") or [] + order, flipped = orient_order(rid, raw_order, stations) + if flipped: + warnings.append(f"สาย {rid}: สลับ station_order ให้ตรงทิศที่รถวิ่งจริง (พิกัดบอกว่าเริ่มฝั่ง {order[0]})") + dirs = OrderedDict() + for rec in recs: + kind, val = direction_of(rec, order[0] if order else None) + key = (kind, val) + d = dirs.setdefault(key, {"recs": [], "label": val if kind == "label" else None}) + d["recs"].append(rec) + + dir_list = [] + dir_seq = 1 + for (kind, val), d in dirs.items(): + stops = [] + for rec in sorted(d["recs"], key=lambda r: r["station_id"]): + entry = {"station_id": rec["station_id"], "times": rec.get("departure_times") or []} + if rec.get("direction_note"): + entry["dir_note"] = rec["direction_note"] + if rec.get("schedule_note"): + entry["note"] = rec["schedule_note"] + stops.append(entry) + stops.sort(key=lambda x: (order.index(x["station_id"]) if x["station_id"] in order else 999)) + dir_id = "all" if kind == "all" else (("from-%s" % val) if kind == "start" else "dir-%d" % dir_seq) + if kind == "label": + dir_seq += 1 + dir_list.append({ + "dir_id": dir_id, + "dir_label": d["label"], + "stops": stops, + }) + n_dup += sum(len(s["times"]) for s in stops) + + # เตือน: ทิศเดียวกันแต่จำนวนเที่ยวของแต่ละจุดไม่เท่ากัน (บ่งชี้ว่ายังแยกทิศไม่ครบ) + for dl in dir_list: + counts = {s["station_id"]: len(s["times"]) for s in dl["stops"] if s["times"]} + if len(set(counts.values())) > 1: + warnings.append( + f"สาย {rid} ทิศ '{dl['dir_label'] or 'ไม่แยกทิศ'}': จำนวนเที่ยวไม่เท่ากันข้ามจุด {counts} " + f"— อาจยังแยกทิศไม่ครบ (ต้องให้เจ้าของข้อมูลยืนยัน)") + + # เตือนจุดจอดที่ไม่มีเวลา (ไม่สร้างข้อมูลปลอม — UI จะขึ้น "ยังไม่มีข้อมูล") + have = {s["station_id"] for dl in dir_list for s in dl["stops"]} + for sid in order: + if sid not in have: + warnings.append(f"สาย {rid}: จุดจอด station {sid} ยังไม่มีเวลาในไฟล์") + + out_routes.append({"route_id": rid, "station_order": order, "directions": dir_list}) + + new = {"schema": 2, "routes": out_routes} + n_time = sum(len(s["times"]) for r in out_routes for d in r["directions"] for s in d["stops"]) + n_distinct = sum(len(r.get("departure_times") or []) for r in records) + + print(f"แปลง {len(records)} record → {len(out_routes)} สาย · " + f"{sum(len(r['directions']) for r in out_routes)} ทิศ · " + f"{sum(len(d['stops']) for r in out_routes for d in r['directions'])} จุด") + print(f"เที่ยวในข้อมูลเดิม (ไม่นับซ้ำ) = {n_distinct} · เก็บในโครงใหม่ = {n_time} " + f"(ส่วนต่าง {n_time - n_distinct} = จุดที่ถูกเก็บในหลายทิศ เช่นจุดแยกทิศ)") + + print(f"\n{'สาย':<7}{'ทิศ':<24}{'จุด':<5}{'เที่ยว':<7}จุดจอดในทิศนั้น") + for r in out_routes: + for d in r["directions"]: + cells = ", ".join(f"{s['station_id']}×{len(s['times'])}" for s in d["stops"]) + print(f"{r['route_id']:<7}{(d['dir_label'] or '(ไม่แยกทิศ)')[:22]:<24}{len(d['stops']):<5}" + f"{sum(len(s['times']) for s in d['stops']):<7}{cells}") + + if warnings: + print(f"\nหมายเหตุ {len(warnings)} ข้อ:") + for w in warnings: + print(" -", w) + + if args.check: + print("\n[--check] ไม่เขียนไฟล์") + return 0 + + Path(args.out).write_text(json.dumps(new, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(f"\nเขียนแล้ว: {Path(args.out).name}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/resource/tools/split-schedules.py b/resource/tools/split-schedules.py new file mode 100644 index 0000000..2ca8a07 --- /dev/null +++ b/resource/tools/split-schedules.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""แตก resource/data/schedules.json → resource/data/scheduleslist/schedules.json (1 ไฟล์ = 1 เส้นทาง) +และเขียน schedules.json ให้เป็น "สารบัญ" (index) ชี้ไปไฟล์ย่อย + +ทำไม: ไฟล์เดียวรวม 14 สายอ่านยาก/แก้ยาก และเวลาแก้ทีละสายต้องเปิดทั้งไฟล์ → แยกเป็นไฟล์ต่อสาย + +รูปแบบไฟล์: + scheduleslist/schedules101.json = { "schema": 2, "route_id": "101", "generated_from": "schedules.json", + "station_order": [...], "directions": [ ... ] } (เนื้อในเหมือนเดิมเป๊ะ) + schedules.json (สารบัญ) = { "schema": 2, "index": true, "dir": "scheduleslist/", + "routes": [ { "route_id": "101", "file": "schedules101.json", ... } ] } + +รัน: python resource/tools/split-schedules.py # เขียนไฟล์จริง + python resource/tools/split-schedules.py --check # ดูผลก่อน ไม่เขียน +หมายเหตุ: ถ้า schedules.json เป็นสารบัญอยู่แล้ว คำสั่งนี้จะไม่ทำอะไร (กันเขียนทับไฟล์ย่อย) — ใช้ merge-schedules.py ย้อนกลับ +""" +import argparse +import json +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DATA = ROOT / "resource" / "data" +LIST_DIR = DATA / "scheduleslist" + + +def jdump(obj): + return json.dumps(obj, ensure_ascii=False, indent=2).replace("\n", "\r\n") + "\r\n" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--check", action="store_true") + args = ap.parse_args() + + src = DATA / "schedules.json" + if not src.exists(): + print("ไม่พบ schedules.json"); return 1 + doc = json.loads(src.read_text(encoding="utf-8")) + if doc.get("index") or "directions" not in json.dumps(doc)[:200]: + if doc.get("index"): + print("schedules.json เป็นสารบัญอยู่แล้ว — ไม่ต้องแตกไฟล์ซ้ำ") + print("(ถ้าต้องการย้อนกลับเป็นไฟล์เดียว ใช้ resource/tools/merge-schedules.py)") + return 0 + routes = doc.get("routes") or [] + if not routes: + print("ไม่พบ routes[] ในไฟล์"); return 1 + + LIST_DIR.mkdir(exist_ok=True) + index_rows = [] + for r in routes: + rid = str(r["route_id"]) + sub = { + "schema": doc.get("schema", 2), + "route_id": r["route_id"], + "generated_from": "schedules.json", + "station_order": r.get("station_order", []), + "directions": r.get("directions", []), + } + fname = "schedules" + rid + ".json" + if not args.check: + (LIST_DIR / fname).write_text(jdump(sub), encoding="utf-8", newline="") + counts = {"n_directions": len(sub["directions"]), + "n_stops": sum(len(d.get("stops") or []) for d in sub["directions"]), + "n_trips": sum(len(s.get("times") or []) for d in sub["directions"] for s in (d.get("stops") or []))} + index_rows.append({"route_id": r["route_id"], "file": fname, **counts}) + + index = { + "schema": doc.get("schema", 2), + "index": True, + "note": "สารบัญชี้ไป scheduleslist/schedules.json (1 ไฟล์ = 1 เส้นทาง) — แก้ไฟล์ย่อยนั้นโดยตรง หรือใช้ resource/data/schedules-editor.html", + "dir": "scheduleslist/", + "routes": index_rows, + } + if not args.check: + src.write_text(jdump(index), encoding="utf-8", newline="") + print(("ตรวจเท่านั้น: " if args.check else "เขียนแล้ว: ") + f"{len(index_rows)} ไฟล์ใน scheduleslist/ + สารบัญ schedules.json") + for row in index_rows: + print(f" {row['file']:<26} ทิศ {row['n_directions']:>2} · จุด {row['n_stops']:>2} · เที่ยว {row['n_trips']:>3}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/resource/tools/stop-km.py b/resource/tools/stop-km.py new file mode 100644 index 0000000..9d9ecff --- /dev/null +++ b/resource/tools/stop-km.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""วัดระยะทาง (กม. ตามเส้นทางจริง) ของทุกจุดจอด แล้วบันทึกลงไฟล์แยก resource/data/stop-km.json + +ทำไมต้องแยกไฟล์: schedules.json เป็นไฟล์ที่ "คนแก้มือ" (ผ่าน Excel/เครื่องมือแก้ไข) — ถ้าเก็บค่าที่คำนวณไว้ในนั้น + พอผู้ใช้กดบันทึกทับจากสำเนาเก่า ค่าที่คำนวณก็หายทั้งชุด → จึงแยกไว้ต่างหาก (ไฟล์นี้เป็น generated) + +ทำไมต้องมี: ระบบ "คำนวณเวลาจากต้นทาง" (ไม่ต้องทำตารางที่จุดกลางทาง) ต้องรู้ว่าจุดอยู่ กม. ที่เท่าไรของเส้น + การวัดทำใน Python ครั้งเดียว แล้วเก็บค่า km ไว้ในไฟล์ → หน้าเว็บไม่ต้องโหลด GIS เลย + +การทำงาน: + 1. อ่าน điểmจอดของแต่ละทิศใน schedules.json (เฉพาะที่มี station_id) + 2. หาพิกัดจาก stations.json (จุดที่เป็น 'จุดขึ้นรถประจำทางอื่นๆ' → หาจาก 8 other_stop.json ตาม route_id) + 3. วัด กม. จากต้นทางตามเส้น geojson-web/.geojson (เลือกปลายที่ใกล้ "จุดที่มีเวลาอยู่แล้ว" ที่สุดเป็นต้นทาง) + 4. เขียนฟิลด์ "km" กลับเข้า stop (ทับค่าเดิมถ้ามี) + รายงานจุดที่วัดไม่ได้ + +รัน: python resource/tools/stop-km.py # เขียนไฟล์ + python resource/tools/stop-km.py --check # ดูผลก่อน ไม่เขียน +""" +import argparse +import json +import math +import re +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DATA = ROOT / "resource" / "data" +OFF_ROUTE_KM = 2.0 # ห่างจากเส้นเกินนี้ = แจ้ง (พิกัดอาจผิด) + + +def hav(a, b): + R = 6371.0 + r = math.pi / 180 + dlat = (b[1] - a[1]) * r + dlng = (b[0] - a[0]) * r + h = math.sin(dlat / 2) ** 2 + math.cos(a[1] * r) * math.cos(b[1] * r) * math.sin(dlng / 2) ** 2 + return 2 * R * math.asin(math.sqrt(h)) + + +def km_on_line(lines, p): + """ระยะตามเส้นจากต้นเส้นถึงจุดที่ใกล้ p ที่สุด + ระยะห่างจากเส้น (กม.)""" + best = None + cum = 0.0 + for line in lines: + for i in range(1, len(line)): + a, b = line[i - 1], line[i] + seg = hav(a, b) + lat0 = math.radians((a[1] + b[1]) / 2) + k = 111.32 + ax, ay = a[0] * math.cos(lat0) * k, a[1] * k + bx, by = b[0] * math.cos(lat0) * k, b[1] * k + px, py = p[0] * math.cos(lat0) * k, p[1] * k + dx, dy = bx - ax, by - ay + L2 = dx * dx + dy * dy + t = 0.0 if not L2 else max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / L2)) + dist = math.hypot(px - (ax + t * dx), py - (ay + t * dy)) + if best is None or dist < best[0]: + best = (dist, cum + t * seg) + cum += seg + return best if best else (None, 0.0) + + +def load_lines(rid): + p = DATA / "geojson-web" / f"{rid}.geojson" + if not p.exists(): + return None + g = json.loads(p.read_text(encoding="utf-8")) + segs = [] + for f in g.get("features", []): + cs = f["geometry"]["coordinates"] + segs += [cs] if f["geometry"]["type"] == "LineString" else cs + segs = [s for s in segs if s] + return segs or None + + +def same_digits(a, b): + na = re.sub(r"\D", "", str(a)) + nb = re.sub(r"\D", "", str(b)) + return bool(na) and len(na) == len(nb) and sorted(na) == sorted(nb) + + +def other_for(rid, others, valid_ids): + """จุดของสายนี้ใน 8 other_stop.json (รองรับรหัสเพี้ยน เช่น 1101 = 1011)""" + want = str(rid) + hit = [o for o in others if str(o["route_id"]) == want] + if hit: + return hit + for o in others: + fid = str(o["route_id"]) + if fid in valid_ids: + continue + cands = [v for v in valid_ids if same_digits(v, fid)] + if len(cands) == 1 and cands[0] == want: + return [o] + return [] + + +def point_of(sid, stations, others_by_route, rid): + st = stations.get(sid) + if not st: + return None, None + lat, lng = st.get("latitude"), st.get("longitude") + if not isinstance(lat, (int, float)) or not isinstance(lng, (int, float)): + # 'จุดขึ้นรถประจำทางอื่นๆ' → เอาจุดจริงของสายนั้น + for o in others_by_route.get(str(rid), []): + la, lo = o.get("latitude"), o.get("longitude") + if isinstance(la, (int, float)) and isinstance(lo, (int, float)): + return (float(lo), float(la)), o.get("station_name_th") + return None, (st.get("station_name_th") or "") + return (float(lng), float(lat)), (st.get("station_name_th") or "") + + +def main(): + ap = argparse.ArgumentParser(description="วัด กม. จากต้นทางของทุกจุดจอด แล้วเขียนลง schedules.json") + ap.add_argument("--check", action="store_true", help="ไม่เขียนไฟล์ แค่รายงาน") + args = ap.parse_args() + + doc = json.loads((DATA / "schedules.json").read_text(encoding="utf-8")) + stations = {s["station_id"]: s for s in json.loads((DATA / "stations.json").read_text(encoding="utf-8"))["stations"]} + others = json.loads((DATA / "8 other_stop.json").read_text(encoding="utf-8"))["other_stop"] + valid_ids = [str(r["route_id"]) for r in json.loads((DATA / "routes.json").read_text(encoding="utf-8"))["routes"]] + others_by_route = {} + for r in doc.get("routes", []): + others_by_route[str(r["route_id"])] = other_for(r["route_id"], others, valid_ids) + by_route = others_by_route + + measured = skipped = offroute = 0 + report = [] + out = {} + for r in doc.get("routes", []): + rid = str(r["route_id"]) + lines = load_lines(rid) + if not lines: + report.append((rid, "(ไม่มีไฟล์ geojson)", None, "—")) + continue + for d in r.get("directions", []): + for s in d.get("stops", []): + pt, name = point_of(s["station_id"], stations, by_route, rid) + if pt is None: + skipped += 1 + report.append((rid, name or f"station {s['station_id']}", None, "ไม่มีพิกัด → วัดไม่ได้")) + pass + continue + dist, km = km_on_line(lines, pt) + out.setdefault(rid, {})[str(s["station_id"])] = round(km, 2) + measured += 1 + if dist is not None and dist > OFF_ROUTE_KM: + offroute += 1 + report.append((rid, name or f"station {s['station_id']}", out[rid][str(s["station_id"])], f"ห่างจากเส้น {dist:.1f} กม. (พิกัดอาจผิด)")) + print(f"วัดระยะได้ {measured} จุด · วัดไม่ได้ {skipped} จุด · ห่างเส้นเกิน {OFF_ROUTE_KM} กม. {offroute} จุด") + if report: + print("\nจุดที่ต้องดู:") + for rid, name, km, why in report: + kms = "—" if km is None else f"{km:g} กม." + print(f" สาย {rid:<5} {name[:34]:<36} {kms:<10} {why}") + + if args.check: + print("\n[--check] ไม่เขียนไฟล์") + return 0 + # เขียนไฟล์แยก (เรียงคีย์ให้อ่านง่าย) + ordered = {rid: out[rid] for rid in sorted(out, key=lambda x: (len(x), x))} + text = json.dumps(ordered, ensure_ascii=False, indent=2).replace("\n", "\r\n") + "\r\n" + (DATA / "stop-km.json").write_text(text, encoding="utf-8", newline="") + # เก็บกวาด: ถ้า schedules.json ยังมีฟิลด์ km ค้างจากรุ่นก่อน ให้เอาออก (ไฟล์ผู้ใช้ต้องสะอาด) + if any("km" in s for r in doc.get("routes", []) for d in r.get("directions", []) for s in d.get("stops", [])): + for r in doc.get("routes", []): + for d in r.get("directions", []): + for st in d.get("stops", []): + st.pop("km", None) + clean = json.dumps(doc, ensure_ascii=False, indent=2).replace("\n", "\r\n") + "\r\n" + (DATA / "schedules.json").write_text(clean, encoding="utf-8", newline="") + print("\nเก็บกวาด: ลบฟิลด์ km ที่ค้างใน schedules.json แล้ว (ไฟล์ผู้ใช้สะอาด)") + print("\nเขียนไฟล์แล้ว: resource/data/stop-km.json") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ui/i18n.js b/ui/i18n.js index b52dacd..5c00751 100644 --- a/ui/i18n.js +++ b/ui/i18n.js @@ -77,6 +77,7 @@ 'map.openInMaps': 'เปิดใน Google Maps', 'map.viewStopPage': 'ดูรายละเอียดป้ายนี้', 'map.km': 'กม.', + 'map.offRoute': 'นอกเส้นทาง', 'map.alongRoute': 'จุดจอดตามเส้นทาง (กม. จากต้นทาง)', 'map.useMyLocation': 'ป้ายใกล้ฉัน', 'map.locating': 'กำลังหาตำแหน่งของคุณ…', @@ -100,7 +101,6 @@ 'home.lead': 'ดูสายรถ, ค้นหาป้าย และเปิดตัวอย่างเส้นทางได้ทันทีจากหน้าแรก', 'home.chooseProvince': 'เลือกจังหวัด', 'home.chooseStation': 'เลือกสถานีขนส่งผู้โดยสาร', - 'home.allStations': 'ทุกสถานีในจังหวัดนี้', 'share.label': 'แชร์ลิงก์สั้น', 'share.copied': 'คัดลอกลิงก์แล้ว', 'share.short': 'ลิงก์สั้น', @@ -139,6 +139,8 @@ 'stops.unitRoutes': 'สายทางหลวง', 'stops.highway': 'ทางหลวง', 'stops.busPrefix': 'สาย', + 'stops.viewSchedule': 'ดูตารางเวลาสาย {n}', + 'stops.viewRoute': 'ดูรายละเอียดสาย {n}', 'stops.noBusLine': 'ยังไม่ระบุสายรถ', 'stops.modeCode': 'ค้นหาด้วยรหัสป้าย', 'stops.modePlace': 'ค้นหาด้วยชื่อสถานที่', @@ -152,6 +154,7 @@ 'stops.reset': 'ล้างค่า', 'stops.section': 'ตอน', 'stops.showing': 'แสดง {a} จาก {b} ป้าย', + 'stops.showAll': 'แสดงป้ายทั้งหมด', 'stops.noResult': 'ไม่พบป้ายหยุดรถที่ตรงกับเงื่อนไข', 'stops.loading': 'กำลังโหลดข้อมูลป้าย…', 'type.terminal': 'สถานีขนส่งผู้โดยสาร', @@ -168,6 +171,10 @@ 'route.overview': 'ภาพรวมของสาย', 'route.contact': 'ติดต่อผู้ประกอบการ', 'route.call': 'โทรสอบถาม', + 'route.openLink': 'เปิดลิงก์', + 'route.link.facebook': 'Facebook', + 'route.link.line': 'LINE Official', + 'route.link.www': 'เว็บไซต์', 'route.vehicle': 'รถบัสประจำสาย', 'route.mapTitle': 'เส้นทางเดินรถ', 'route.photos': 'รูปรถประจำเส้นทางในเครือข่าย', @@ -192,6 +199,31 @@ 'stop.showing': 'แสดง {a} จาก {b} สาย', 'stop.mapInfo': 'แผนที่และข้อมูลป้าย', 'stop.nextArrival': 'เที่ยวถัดไป', + 'stop.subGeneric': 'จุดจอดใน{city} · ดูเวลารถทุกสายที่ผ่านป้ายนี้ได้ในหน้าเดียว', + 'stop.thisStop': 'ป้ายนี้', + 'stop.statRoutes': 'จำนวนสายรถ', + 'stop.statTrips': 'เที่ยวต่อวัน', + 'stop.statHours': 'เวลาบริการ', + 'stop.statType': 'ประเภท', + 'stop.nRoutes': '{n} สาย', + 'stop.tripsPerDay': '{n} รอบ/วัน', + 'stop.tripsPerDay1': '{n} รอบ/วัน', + 'stop.nRoutes1': '{n} สาย', + 'stop.noRoutes': 'ยังไม่มีสายรถที่บันทึกว่าผ่านป้ายนี้', + 'stop.noTimes': 'ยังไม่มีข้อมูลเวลาเดินรถที่ป้ายนี้', + 'stop.tomorrow': 'พรุ่งนี้', + 'stop.nextAt': 'ถัดไป', + 'stop.notFound': 'ไม่พบป้ายนี้', + 'stop.notFoundSub': 'ไม่พบรหัสป้าย “{code}” ในระบบ — ตรวจรหัสหรือกลับไปหน้ารายการป้าย', + 'stop.nearbySub': 'สถานที่น่าสนใจและจุดแวะระหว่างรอรถ', + 'stop.otherStopsTitle': 'จุดขึ้นรถประจำทางอื่นๆ · สาย {n} ({m} จุด)', + 'stop.otherMore': '(+{n} จุด)', + 'stop.otherStopsAll': 'จุดขึ้นรถประจำทางอื่นๆ ทั้งหมด ({m} จุด)', + 'stop.noCoord': 'ยังไม่มีพิกัด', + 'stop.open': 'เปิด', + 'stop.close': 'ปิด', + 'stop.nowAtStop': 'เวลาปัจจุบัน ณ ป้ายนี้', + 'stop.autoNext': 'กำลังคำนวณเที่ยวถัดไปอัตโนมัติ', // ทั่วไป 'common.backHome': '← กลับหน้าแรก', @@ -216,11 +248,6 @@ 'credits.icons': 'ไอคอน — Lucide', 'credits.fonts': 'ฟอนต์ — Google Fonts', 'credits.map': 'แผนที่', - 'credits.images': 'รูปภาพประกอบ', - 'credits.logos': 'โลโก้ผู้สนับสนุนและพาร์ทเนอร์', - 'credits.data': 'ข้อมูลการเดินรถ', - 'credits.pwa': 'โหมดออฟไลน์ (PWA / Service Worker)', - 'credits.notes': 'หมายเหตุ', 'common.back': 'ย้อนกลับ', 'check.scheduleAll': 'ตารางเวลาเดินรถทุกจุดจอด', 'check.title': 'ตารางเวลาเดินรถ', @@ -231,6 +258,20 @@ 'check.kpiNext': 'รอบถัดไป', 'check.direction': 'ทิศทาง', 'check.atStop': 'ตารางเดินรถ ณ', + 'check.dayWeekday': 'Weekday timetable (Mon–Fri)', + 'check.dayHoliday': 'Weekend/holiday timetable', + 'check.dayMixed': 'This direction mixes weekday and holiday times — not split by day yet', + 'check.dayUnknown': 'Timetable day not specified (showing all days)', + 'check.dayOfWeek': 'today is', + 'time.estimated': '~ Estimated from the origin (not an operator timetable)', + 'time.derived': '~ ตารางจากการคำนวณ (จาก {base} {n} นาที) — อาจเปลี่ยนแปลงตามการจราจรจริง', + 'check.dayWeekday': 'ตารางวันทำงาน (จ–ศ)', + 'check.dayHoliday': 'ตารางวันหยุด (ส–อา/นักขัตฤกษ์)', + 'check.dayMixed': 'ทิศนี้มีทั้งตารางวันทำงานและวันหยุดในตัวเดียวกัน — ยังไม่แยกตามวัน', + 'check.dayUnknown': 'ยังไม่ระบุวันของตาราง (แสดงทุกวัน)', + 'check.dayOfWeek': 'วันนี้', + 'time.estimated': '~ เวลาคำนวณจากต้นทาง (ประมาณ — ไม่ใช่ตารางของผู้ประกอบการ)', + 'time.derived': '~ Computed timetable (from {base} {n} min) — may change with real traffic conditions', 'check.now': 'เวลาปัจจุบัน', 'check.nextAt': 'เที่ยวถัดไป', 'check.noMoreToday': 'ไม่มีรถเหลือในวันนี้แล้ว', @@ -298,6 +339,7 @@ 'map.openInMaps': 'Open in Google Maps', 'map.viewStopPage': 'View this stop', 'map.km': 'km', + 'map.offRoute': 'off route', 'map.alongRoute': 'Stops along the route (km from origin)', 'map.useMyLocation': 'Stops near me', 'map.locating': 'Finding your location…', @@ -320,7 +362,6 @@ 'home.lead': 'Browse routes, find stops, and preview a route right from this page', 'home.chooseProvince': 'Select Province', 'home.chooseStation': 'Select Terminal', - 'home.allStations': 'All terminals in this province', 'share.label': 'Share short link', 'share.copied': 'Link copied', 'share.short': 'Short link', @@ -358,6 +399,8 @@ 'stops.unitRoutes': 'highways', 'stops.highway': 'Highway', 'stops.busPrefix': 'Route', + 'stops.viewSchedule': 'View schedule for route {n}', + 'stops.viewRoute': 'View route {n}', 'stops.noBusLine': 'No bus line listed', 'stops.modeCode': 'Search by stop code', 'stops.modePlace': 'Search by place name', @@ -371,6 +414,7 @@ 'stops.reset': 'Clear', 'stops.section': 'Section', 'stops.showing': 'Showing {a} of {b} stops', + 'stops.showAll': 'Show all stops', 'stops.noResult': 'No stops match your search', 'stops.loading': 'Loading stop data…', 'type.terminal': 'Passenger terminal', @@ -386,6 +430,10 @@ 'route.overview': 'Route overview', 'route.contact': 'Contact operator', 'route.call': 'Call us', + 'route.openLink': 'Open link', + 'route.link.facebook': 'Facebook', + 'route.link.line': 'LINE Official', + 'route.link.www': 'Website', 'route.vehicle': 'Route vehicle', 'route.mapTitle': 'Route map', 'route.photos': 'Buses on this network', @@ -409,6 +457,31 @@ 'stop.showing': 'Showing {a} of {b} routes', 'stop.mapInfo': 'Map & stop info', 'stop.nextArrival': 'Next arrival', + 'stop.subGeneric': 'A stop in {city} · see every route that passes here on one page', + 'stop.thisStop': 'this stop', + 'stop.statRoutes': 'Routes', + 'stop.statTrips': 'Departures/day', + 'stop.statHours': 'Service hours', + 'stop.statType': 'Type', + 'stop.nRoutes': '{n} routes', + 'stop.tripsPerDay': '{n} trips/day', + 'stop.tripsPerDay1': '{n} trip/day', + 'stop.nRoutes1': '{n} route', + 'stop.noRoutes': 'No routes recorded for this stop yet', + 'stop.noTimes': 'No departure times for this stop yet', + 'stop.tomorrow': 'Tomorrow', + 'stop.nextAt': 'Next', + 'stop.notFound': 'Stop not found', + 'stop.notFoundSub': 'No stop with code “{code}” — check the code or go back to the stop list', + 'stop.nearbySub': 'Places of interest and stops to wait for your bus', + 'stop.otherStopsTitle': 'Other boarding points · route {n} ({m} stops)', + 'stop.otherMore': '(+{n} stops)', + 'stop.otherStopsAll': 'All other boarding points ({m} stops)', + 'stop.noCoord': 'No coordinates yet', + 'stop.open': 'Open', + 'stop.close': 'Close', + 'stop.nowAtStop': 'Current time at this stop', + 'stop.autoNext': 'Next departure is calculated automatically', 'common.backHome': '← Back to home', 'common.backStops': '← Back to stops', @@ -432,11 +505,6 @@ 'credits.icons': 'Icons — Lucide', 'credits.fonts': 'Fonts — Google Fonts', 'credits.map': 'Maps', - 'credits.images': 'Images', - 'credits.logos': 'Sponsor & partner logos', - 'credits.data': 'Transit data', - 'credits.pwa': 'Offline mode (PWA / Service Worker)', - 'credits.notes': 'Notes', 'common.back': 'Back', 'check.scheduleAll': 'Departure times at every stop', 'check.title': 'Departure Schedule', diff --git a/ui/index.html b/ui/index.html index 5be5b1d..db0715c 100644 --- a/ui/index.html +++ b/ui/index.html @@ -304,6 +304,8 @@ + + @@ -391,6 +393,7 @@ +
diff --git a/ui/map.css b/ui/map.css index 83acaad..91cfdc5 100644 --- a/ui/map.css +++ b/ui/map.css @@ -124,6 +124,11 @@ .at-km-dot { width: 9px; height: 9px; border-radius: 3px; background: #f2a900; flex: none; } .at-km-name { flex: 1; font-weight: 600; } .at-km-val { font-variant-numeric: tabular-nums; font-weight: 700; color: #14532d; } +/* จุดจอดที่ไม่มีหน้ารายละเอียด (มาจาก 8 other_stop.json) — ไม่ใช่ลิงก์ */ +.at-km-row.is-plain { cursor: default; } +.at-km-row.is-plain .at-km-dot { background: #7a4cc0; } +.at-km-row.is-plain:hover .at-km-name { color: inherit; text-decoration: none; } +.at-km-row .at-km-val.is-off { color: #a3560f; font-weight: 600; font-size: .78rem; } /* ---------- ป้ายใกล้ฉัน ---------- */ .at-near-msg { margin: 14px 0 0; color: #6b7268; font-size: .86rem; } @@ -135,3 +140,16 @@ .at-near-name { font-weight: 700; font-size: .9rem; } .at-near-meta { grid-column: 1; color: #6b7268; font-size: .76rem; } .at-near-dist { grid-column: 2; grid-row: 1 / span 2; font-variant-numeric: tabular-nums; font-weight: 800; color: #14532d; white-space: nowrap; } + +/* ---------- กัน CSS ภายนอกทำลายขนาด SVG ของ Leaflet ---------- + responsive.css ตั้ง `img, svg, video { max-width: 100%; height: auto; }` และบาง partial + เคยตั้ง `.mu-map-card svg { width: 100%; height: auto; }` → ทำให้ viewport SVG ของ Leaflet + (ซึ่งถูกวางใน pane ขนาด 0x0) ยุบเป็น 0x0 แล้ว "เส้นทางไม่แสดง" ทั้งที่ถูกวาดแล้ว + Leaflet กำหนดขนาดเองผ่าน attribute width/height เสมอ — ห้าม CSS อื่นทับ */ +.at-map svg.leaflet-zoom-animated, +.at-map canvas.leaflet-zoom-animated { + width: auto; + height: auto; + max-width: none; + max-height: none; +} diff --git a/ui/map.js b/ui/map.js index 96a47de..a9d2e54 100644 --- a/ui/map.js +++ b/ui/map.js @@ -20,6 +20,11 @@ window.ATMap = (function () { 'use strict'; var DEF_BASE = '../resource/data/'; + /* station_id 8 = "จุดขึ้นรถประจำทางอื่นๆ" (ใช้ร่วมหลายสาย) → ต้องจับคู่ route_id + ในไฟล์ '8 other_stop.json' เพื่อเอาชื่อ/พิกัดจริงของสายนั้น (สายเดียวมีได้หลายจุด) */ + var OTHER_STOP_ID = 8; + var OTHER_STOP_FILE = '8%20other_stop.json'; + var OFF_ROUTE_M = 2000; /* ห่างจากเส้นเกินนี้ → แจ้ง "นอกเส้นทาง" */ var TILES = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'; var ATTRIB = '© OpenStreetMap'; var NEAR_M = 40; /* ป้ายอยู่ "บนเส้นทาง" ถ้าใกล้ ≤ 40 ม. */ @@ -118,16 +123,97 @@ window.ATMap = (function () { } function stops(o) { return loadJson('busstop_list.json', 'stops', o).then(function (d) { return d || []; }); } function stationList(o) { return loadJson('stations.json', 'stations', o).then(function (d) { return (d || {}).stations || []; }); } + function otherStopList(o) { return loadJson(OTHER_STOP_FILE, 'otherStops', o).then(function (d) { return (d || {}).other_stop || []; }); } + function routeList(o) { return loadJson('routes.json', 'routes', o).then(function (d) { return (d || {}).routes || []; }); } + + /* จุดจอดตามเส้นทาง = routes.json → station_ids (ตามลำดับของสาย) + - station_id 8 → จับคู่ route_id ใน '8 other_stop.json' (ถ้าไม่มีคู่ จับคู่ไม่ได้ → ใช้สถานี 8 ตามเดิม) + - กม. จากต้นทาง = วัดตามเส้น geometry โดยเลือกปลายที่ใกล้จุดจอดแรกที่สุดเป็น "ต้นทาง" + - พิกัดที่ห่างจากเส้นเกิน OFF_ROUTE_M → ขึ้น "นอกเส้นทาง" แทนตัวเลข กม. (กันเลขหลอก) */ + function routeStopRows(route, stations, others, main, validIds) { + var byId = {}; + stations.forEach(function (st) { byId[st.station_id] = st; }); + + var stops = []; + (route.station_ids || []).forEach(function (sid) { + if (sid === OTHER_STOP_ID) { + /* จับคู่ route → ชื่อสถานที่จริง (รองรับรหัสเพี้ยน เช่น 1101 = สาย 1011) ผ่าน OtherStop */ + var hit = (window.OtherStop && OtherStop.forRouteAll) + ? OtherStop.forRouteAll(others, route.route_id, validIds) + : (others || []).filter(function (o) { return String(o.route_id) === String(route.route_id); }); + if (hit.length) { + hit.forEach(function (o) { + /* แตกเป็น "จุดจริง" ทีละจุด — ชื่อ ↔ พิกัด จับคู่ตามลำดับ (จุดที่ไม่มีพิกัด = ไม่ปักหมุด) */ + var subs = (window.OtherStop && OtherStop.stopsOf) ? OtherStop.stopsOf(o) : []; + if (!subs.length) subs = [{ name: o.station_name_th, hasCoord: false, lat: null, lng: null }]; + subs.forEach(function (sub) { + stops.push({ + name: sub.name, + pt: sub.hasCoord ? [sub.lng, sub.lat] : null, + code: null, + note: o.note || null + }); + }); + }); + return; /* จับคู่ได้ → ไม่ใช้ชื่อสถานีรวม */ + } + } + var st = byId[sid]; + if (st) stops.push({ name: st.station_name_th, pt: pointOf(st), code: st.station_code }); + }); + + var total = lineLengthKm([main]); + var first = stops.filter(function (s) { return s.pt; })[0]; + var fromEnd = first ? kmFromStart(main, first.pt).km > total / 2 : false; + + stops.forEach(function (s) { + if (!s.pt) { s.km = null; s.off = false; return; } + var k = kmFromStart(main, s.pt); + var km = fromEnd ? total - k.km : k.km; + s.off = k.d > OFF_ROUTE_M; + s.km = Math.max(0, km).toFixed(1); + }); + return stops; + } /* ---------- องค์ประกอบแผนที่ ---------- */ + /* แผนที่ทั้งหมดที่สร้างในหน้านี้ (ไว้จัดการ resize + ตรวจสอบ) */ + var MAPS = []; + + function mapOptions() { + return { + zoomControl: true, + attributionControl: true, + scrollWheelZoom: true, /* ล้อเมาส์: หมุนเข้า/ออก = ซูม */ + touchZoom: true, /* มือถือ: ใช้นิ้ว 2 นิ้วจีบ/กาง = ซูม */ + doubleClickZoom: true, + boxZoom: true, + keyboard: true, + wheelDebounceTime: 40 /* หน่วงนิดเดียว ไม่ให้ซูมกระโดดตอนหมุนเร็ว */ + }; + } + function makeMap(el) { var offline = navigator.onLine === false; if (offline) el.classList.add('is-offline'); - var map = L.map(el, { zoomControl: true, attributionControl: true, scrollWheelZoom: false }); + var map = L.map(el, mapOptions()); map.setView([14.588, 100.455], 11); if (!offline) L.tileLayer(TILES, { maxZoom: 18, minZoom: 8, attribution: ATTRIB }).addTo(map); + MAPS.push({ map: map, el: el, bounds: null }); return { map: map, offline: offline }; } + + /* ถ้าหน้าต่างเปลี่ยนขนาด (หรือหมุนมือถือ) → อัปเดตขนาด + ซูมให้พอดีเส้นทางอีกครั้ง */ + var resizeTimer = null; + window.addEventListener('resize', function () { + clearTimeout(resizeTimer); + resizeTimer = setTimeout(function () { + MAPS.forEach(function (rec) { + rec.map.invalidateSize(); + if (rec.bounds) rec.map.fitBounds(rec.bounds, { padding: [24, 24], maxZoom: 15 }); + }); + }, 200); + }); function pinIcon(kind) { return L.divIcon({ className: 'at-pin-wrap', html: '', iconSize: [16, 16], iconAnchor: [8, 8] }); } @@ -152,13 +238,40 @@ window.ATMap = (function () { var all = []; latlngs.forEach(function (l) { all = all.concat(l); }); if (!all.length) return; - if (all.length === 1) { map.setView(all[0], 14); return; } - map.fitBounds(L.latLngBounds(all), { padding: [24, 24] }); + var rec = mapsFor(map); + if (all.length === 1) { + if (rec) rec.bounds = L.latLngBounds(all); + map.setView(all[0], 14); + return; + } + var bounds = L.latLngBounds(all); + if (rec) rec.bounds = bounds; + map.invalidateSize(); /* ให้แน่ใจว่าขนาดถูกก่อนคำนวณซูม */ + map.fitBounds(bounds, { padding: [24, 24], maxZoom: 15 }); + } + + function mapsFor(map) { + for (var i = 0; i < MAPS.length; i++) if (MAPS[i].map === map) return MAPS[i]; + return null; } function mapsLink(lat, lng) { return 'https://www.google.com/maps/search/?api=1&query=' + lat + ',' + lng; } + /* วาดเส้นทาง: ขอบสีครีม (เห็นชัดบนพื้นแผนที่) แล้วทับด้วยเส้นสีจริง 5px ตาม DESIGN.md §5 */ + function drawLines(group, specs) { + specs.forEach(function (sp) { + L.polyline(sp.latlngs, { + color: '#fffdf6', weight: LINE_W + 4, opacity: 0.95, lineJoin: 'round', lineCap: 'round', smoothFactor: 0.6 + }).addTo(group); + }); + specs.forEach(function (sp) { + L.polyline(sp.latlngs, { + color: sp.color, weight: LINE_W, opacity: 1, lineJoin: 'round', lineCap: 'round', smoothFactor: 0.6 + }).addTo(group); + }); + } + /* ป้ายหยุดรถ: hover = ข้อมูลย่อ · คลิก = popup (ประเภท/กม./ด้านทาง/สายที่ผ่าน + Google Maps) */ function drawShelters(map, hits, group) { hits.forEach(function (h) { @@ -251,13 +364,16 @@ window.ATMap = (function () { if (!list.length) return; list.forEach(function (x) { var li = document.createElement('li'); - var a = document.createElement('a'); - a.href = x.href; - a.className = 'at-km-row'; - a.innerHTML = '' + + var row = document.createElement(x.href ? 'a' : 'div'); + if (x.href) row.href = x.href; + row.className = 'at-km-row' + (x.href ? '' : ' is-plain'); + if (x.note) row.title = x.note; + var val = x.off ? '' + esc(t('map.offRoute')) + '' + : (x.km === null || x.km === '' ? '–' : x.km + ' ' + esc(t('map.km'))); + row.innerHTML = '' + '' + esc(x.name) + '' + - '' + x.km + ' ' + esc(t('map.km')) + ''; - li.appendChild(a); + '' + val + ''; + li.appendChild(row); host.appendChild(li); }); var wrap = host.closest('.at-km-wrap'); @@ -282,9 +398,7 @@ window.ATMap = (function () { var m = makeMap(el), map = m.map, group = L.layerGroup().addTo(map); var latlngs = toLatLngs(lines); - latlngs.forEach(function (l) { - L.polyline(l, { color: LINE_MAIN, weight: LINE_W, opacity: 1, lineJoin: 'round', lineCap: 'round' }).addTo(group); - }); + drawLines(group, latlngs.map(function (l) { return { latlngs: l, color: LINE_MAIN }; })); /* ต้นทาง/ปลายทาง */ [[latlngs[0][0], t('map.origin')], [latlngs[latlngs.length - 1][latlngs[latlngs.length - 1].length - 1], t('map.destination')]] .forEach(function (e) { @@ -292,23 +406,36 @@ window.ATMap = (function () { .bindTooltip(esc(e[1]), { direction: 'top', offset: [0, -8] }).addTo(group); }); - Promise.all([stopsNear(lines, opts), stationsNear(lines, STATION_NEAR_M, opts)]).then(function (res) { - var shelters = res[0], sts = res[1]; + Promise.all([stopsNear(lines, opts), stationsNear(lines, STATION_NEAR_M, opts), + stationList(opts), routeList(opts), otherStopList(opts)]).then(function (res) { + var shelters = res[0], sts = res[1], stations = res[2], routesDoc = res[3], others = res[4]; drawShelters(map, shelters, group); drawStations(map, sts, opts, group); fitAll(map, latlngs); - /* รายการสถานี + กม. จากต้นทาง (เรียงตามเส้นทาง) */ + /* จุดจอดตามเส้นทาง + กม. จากต้นทาง — ใช้ routes.json → station_ids เป็นหลัก + (station 8 → จับคู่ route_id ใน 8 other_stop.json) ถ้าหา route ไม่ได้จึงใช้ระยะใกล้เส้นแบบเดิม */ var main = longest(lines); - var rows = sts.map(function (h) { - var pt = pointOf(h.station); - var k = kmFromStart(main, pt); - return { name: h.station.station_name_th, km: k.km.toFixed(1), href: href(opts, h.station.station_code), _sort: k.km }; - }).sort(function (a, b) { return a._sort - b._sort; }); + var route = (routesDoc || []).filter(function (r) { return String(r.route_id) === String(routeId); })[0]; + var rows; + if (route && (route.station_ids || []).length) { + rows = routeStopRows(route, stations, others, main, (routesDoc || []).map(function (r) { return String(r.route_id); })).map(function (x) { + return { name: x.name, km: x.km, off: x.off, note: x.note, href: x.code ? href(opts, x.code) : null }; + }).sort(function (a, b) { /* เรียงตาม กม. ตามเส้นทาง (อ่านเป็นเส้นทางเดินรถ) */ + if (a.km === null || a.km === '') return 1; + if (b.km === null || b.km === '') return -1; + return parseFloat(a.km) - parseFloat(b.km); + }); + } else { + rows = sts.map(function (h) { + var k = kmFromStart(main, pointOf(h.station)); + return { name: h.station.station_name_th, km: k.km.toFixed(1), off: false, href: href(opts, h.station.station_code) }; + }).sort(function (a, b) { return parseFloat(a.km) - parseFloat(b.km); }); + } renderKmList('route-map-list', rows); var parts = ['' + esc(routeId) + ' · ' + esc(t('map.captionRoute', { km: lineLengthKm(lines).toFixed(1), n: shelters.length }))]; - if (sts.length) parts.push(esc(t('map.stations')) + ' ' + sts.length + ''); + if (rows.length) parts.push(esc(t('map.stations')) + ' ' + rows.length + ''); if (m.offline) parts.push('' + esc(t('map.offline')) + ''); caption(el, parts.join(' · ')); }); @@ -332,6 +459,9 @@ window.ATMap = (function () { var list = res[0], routes = (res[1] || {}).routes || []; var st = list.filter(function (s) { return s.station_code === code; })[0]; var serving = st ? routes.filter(function (r) { return (r.station_ids || []).indexOf(st.station_id) !== -1; }) : []; + if (opts.onlyRoutes && opts.onlyRoutes.length) { + serving = serving.filter(function (r) { return opts.onlyRoutes.indexOf(String(r.route_id)) !== -1; }); + } var ids = serving.map(function (r) { return r.route_id; }); if (!st || !ids.length) { @@ -342,7 +472,7 @@ window.ATMap = (function () { Promise.all(ids.map(function (id) { return loadGeo(id, opts); })).then(function (geos) { var m = makeMap(el), map = m.map, group = L.layerGroup().addTo(map); - var all = [], allLines = [], legendRows = [], drawn = 0; + var all = [], allLines = [], legendRows = [], drawn = 0, specs = []; geos.forEach(function (g, idx) { var lines = flatten(g); @@ -351,7 +481,7 @@ window.ATMap = (function () { drawn++; allLines = allLines.concat(lines); toLatLngs(lines).forEach(function (l) { - L.polyline(l, { color: color, weight: LINE_W, opacity: 1, lineJoin: 'round', lineCap: 'round' }).addTo(group); + specs.push({ latlngs: l, color: color }); all.push(l); }); legendRows.push({ color: color, label: t('map.route') + ' ' + ids[idx] }); @@ -362,13 +492,17 @@ window.ATMap = (function () { caption(el, '' + esc(t('map.empty')) + ''); return; } + drawLines(group, specs); stopsNear(allLines, opts).then(function (shelters) { drawShelters(map, shelters, group); - var stPt = pointOf(st); + /* opts.focus = จุดจริงของสายที่เลือก (เช่น จุดขึ้นรถประจำทางอื่นๆ → วัดสีบัวทอง) */ + var stPt = opts.focus ? pointOf(opts.focus) : pointOf(st); + var focusFirst = (opts.focus && window.OtherStop && OtherStop.firstName) ? OtherStop.firstName(opts.focus) : null; + var pinName = focusFirst || (opts.focus && opts.focus.station_name_th) || st.station_name_th; if (stPt) { L.marker([stPt[1], stPt[0]], { icon: pinIcon('here'), zIndexOffset: 1000 }) - .bindTooltip('' + esc(st.station_name_th) + '
' + esc(t('map.thisStop')), { direction: 'top', offset: [0, -11] }) + .bindTooltip('' + esc(pinName) + '
' + esc(t('map.thisStop')), { direction: 'top', offset: [0, -11] }) .addTo(group); all.push([[stPt[1], stPt[0]]]); } @@ -473,7 +607,7 @@ window.ATMap = (function () { function drawNearMap(box, near, me) { var offline = navigator.onLine === false; - var map = L.map(box, { zoomControl: true, attributionControl: true, scrollWheelZoom: false }); + var map = L.map(box, mapOptions()); map.setView([me[1], me[0]], 13); if (!offline) L.tileLayer(TILES, { maxZoom: 18, minZoom: 8, attribution: ATTRIB }).addTo(map); else box.classList.add('is-offline'); @@ -494,6 +628,7 @@ window.ATMap = (function () { return { route: route, forStop: forStop, nearMe: nearMe, - NEAR_M: NEAR_M, LINE_MAIN: LINE_MAIN + NEAR_M: NEAR_M, LINE_MAIN: LINE_MAIN, + maps: MAPS /* ไว้ตรวจสอบ/ทดสอบจากคอนโซล */ }; })(); diff --git a/ui/partials/busDetail.html b/ui/partials/busDetail.html index 2dbf373..4157e23 100644 --- a/ui/partials/busDetail.html +++ b/ui/partials/busDetail.html @@ -86,6 +86,10 @@ background: linear-gradient(135deg, #7a4cc0, #b07ce0); color: #fff; } .mu-contact-item .ic-wrap.tone-green { background: linear-gradient(135deg, #1f8765, #51c39c); } + .mu-contact-item .ic-wrap.tone-sky { background: linear-gradient(135deg, #1877f2, #4a9bf8); } + .mu-contact-item .ic-wrap.tone-purple { background: linear-gradient(135deg, #7a4cc0, #a583e0); } + .mu-contact-item .mu-link-go { flex: 0 0 auto; display: flex; align-items: center; color: #7a4cc0; opacity: .8; } + .mu-contact-item:hover .mu-link-go { opacity: 1; transform: translateX(2px); } .mu-contact-item .ic-wrap svg { width: 22px; height: 22px; } .mu-contact-item .txt { flex: 1; min-width: 0; } .mu-contact-item .txt strong { display: block; color: #1f2a44; font-size: .98rem; margin-bottom: 2px; } @@ -104,7 +108,8 @@ padding: 16px; box-shadow: 0 4px 14px rgba(20, 40, 90, .06); } - .mu-map-card svg { width: 100%; height: auto; display: block; } + /* (ตัดกฎ .mu-map-card svg เดิมออก — แผนที่ SVG นิ่งถูกแทนด้วย Leaflet + และกฎนี้ทำให้ SVG ของ Leaflet ยุบเป็น 0x0 จนเส้นทางไม่แสดง) */ .mu-summary-grid { gap: 14px; } diff --git a/ui/partials/busDetail.init.js b/ui/partials/busDetail.init.js index 4cf7e9f..891dd22 100644 --- a/ui/partials/busDetail.init.js +++ b/ui/partials/busDetail.init.js @@ -84,17 +84,38 @@ } function telHref(p) { return 'tel:' + String(p == null ? '' : p).replace(/[^\d+]/g, ''); } - /* ---------- การ์ดติดต่อ (LINE + QR + เบอร์โทรทุกเบอร์จาก routes.json) ---------- */ + /* ---------- ลิงก์ติดต่อ (web_url ใน routes.json) — ไอคอน/ชื่อ/สี เปลี่ยนตามชนิด URL ---------- + facebook → ไอคอน facebook + โทนฟ้า · line (line.me / lin.ee / linevoom) → LINE + โทนเขียว + อื่น ๆ (www) → ไอคอนลูกโลก + โทนม่วง */ + var LINK_KINDS = [ + { key: 'facebook', icon: 'ic-facebook', tone: 'tone-sky', match: /facebook\.com|fb\.(me|com)/i }, + { key: 'line', icon: 'ic-message-circle', tone: 'tone-green', match: /line\.me|lin\.ee|linevoom|line\.at/i }, + { key: 'www', icon: 'ic-globe', tone: 'tone-purple', match: /^https?:/i } + ]; + function linkKind(url) { + var u = String(url || '').trim(); + if (!u) return null; + for (var i = 0; i < LINK_KINDS.length; i++) { if (LINK_KINDS[i].match.test(u)) return LINK_KINDS[i]; } + return { key: 'www', icon: 'ic-globe', tone: 'tone-purple' }; + } + function prettyUrl(url) { + return String(url || '').trim().replace(/^https?:\/\//i, '').replace(/\/+$/, ''); + } + + /* ---------- การ์ดติดต่อ (LINE + QR + ลิงก์ + เบอร์โทรจาก routes.json) ---------- */ function buildContact(rid, route, cap) { var host = $('route-contact'); if (!host) return; host.innerHTML = ''; + var kind = linkKind(route.web_url); var line = document.createElement('div'); line.className = 'mu-contact-item'; line.innerHTML = - '' + - '
LINE Official
'; + '' + + '
' + esc(kind ? t('route.link.' + kind.key) : 'LINE Official') + '' + + '
'; var qr = document.createElement('img'); qr.className = 'mu-qr-img'; qr.loading = 'lazy'; @@ -120,6 +141,21 @@ '
' + esc(t('route.call')) + '' + esc(fmtPhone(p)) + '
'; host.appendChild(a); }); + + /* ปุ่ม "เปิดลิงก์" แยกต่างหาก — ชัดเจนบนมือถือ (แสดงเมื่อ routes.json มี web_url) */ + if (kind) { + var open = document.createElement('a'); + open.className = 'mu-contact-item'; + open.href = String(route.web_url).trim(); + open.target = '_blank'; + open.rel = 'noopener noreferrer'; + open.innerHTML = + '' + + '
' + esc(t('route.openLink')) + '' + esc(prettyUrl(route.web_url)) + '
' + + ''; + host.appendChild(open); + host.hidden = false; + } } /* ---------- รอบต่อวัน / รอบถัดไป จาก schedules.json ---------- */ @@ -137,8 +173,8 @@ return uniqTimes[0]; /* หมดรอบของวันนี้ → รอบแรกของวันถัดไป */ } function loadTrips(rid) { - return fetchJSON(DATA + 'schedules.json').then(function (d) { - var recs = (d && (d.schedules || d)) || []; + return Schedules.load().then(function (sd) { return Schedules.normSub(sd); }).then(function (d) { + var recs = window.Schedules ? Schedules.records(d) : ((d && (d.schedules || d)) || []); var out = []; recs.forEach(function (r) { if (String(r.route_id) === String(rid)) out = out.concat(r.departure_times || []); diff --git a/ui/partials/busStop.html b/ui/partials/busStop.html index a024bca..f7a6959 100644 --- a/ui/partials/busStop.html +++ b/ui/partials/busStop.html @@ -240,7 +240,11 @@ } .mu-toolbar-actions { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 12px; } - .mu-toolbar-count { margin: 10px 0 0; font-size: .84rem; color: #6f7b95; } + .mu-show-more { display: flex; justify-content: center; margin: 14px 0 4px; } + .mu-show-more .mu-btn { min-width: 220px; } + .mu-stop-card.is-stub { min-height: 120px; background: #faf8ff; border: 1px dashed #ddd2f2; box-shadow: none; } + + .mu-toolbar-count { margin: 10px 0 0; font-size: .84rem; color: #6f7b95; } .mu-toolbar-count b { color: #7a4cc0; font-variant-numeric: tabular-nums; } /* ===== การ์ดป้าย ===== */ @@ -295,6 +299,10 @@ font-weight:700; } .mu-chip.route { background: #f3ecff; color:#6d28d9; border-color: #e0d6f5; } + /* ชิปสายที่เป็นลิงก์ → ไปหน้าเช็กเวลาของสายนั้น (หน้าตาเหมือนชิปเดิม + มี hover/focus) */ + a.mu-chip.route { text-decoration: none; cursor: pointer; } + a.mu-chip.route:hover { background:#e9dcff; border-color:#cdb5f2; } + a.mu-chip.route:focus-visible { outline: 2px solid #7a4cc0; outline-offset: 2px; } /* รหัสป้าย = ม่วง-ขาว แบบเดียวกับป้ายสายรถ */ .mu-chip.count.stop-code { background: linear-gradient(135deg, #7a4cc0, #b07ce0); @@ -449,6 +457,10 @@
    + +
    + +
    diff --git a/ui/partials/busStop.init.js b/ui/partials/busStop.init.js index 67f5f27..1c30853 100644 --- a/ui/partials/busStop.init.js +++ b/ui/partials/busStop.init.js @@ -25,8 +25,10 @@ 'use strict'; var DATA_URL = '../resource/data/busstop_list.json'; - var IMG_DIR = '../.image/stops/'; - var IMG_EXT = '.jpg'; + var ROUTES_URL = '../resource/data/routes.json'; /* ใช้ยืนยันว่าสายมีอยู่จริง ก่อนทำชิปเป็นลิงก์ */ + var IMG_DIR = '../.image/stops/'; /* รูปป้ายริมทาง: pad5(กม.) เช่น 36020.jpg (ชุดเดิม) */ + var STATION_IMG_DIR = '../.image/stations/'; /* รูปสถานี (ตัวอาคาร): .jpg ตาม stations.json */ + var IMG_EXTS = ['jpg', 'jpeg', 'webp', 'png']; /* ไล่ลองนามสกุล (รองรับ .jpeg) */ var PLACEHOLDER = '../.image/icons/minibus-512x512.png'; function t(key, vars) { @@ -49,14 +51,32 @@ .catch(function () { return null; }); } - /* ---------- รูป: ลองรูปจริงก่อน ถ้าไม่มีค่อยใช้ placeholder ---------- */ - function resolveImage(km) { - var code = pad5(km); - if (!code) return Promise.resolve(PLACEHOLDER); - var url = IMG_DIR + code + IMG_EXT; + /* ---------- รูป: รูปสถานี (.jpg) ก่อน → รูปป้ายริมทาง (pad5 กม.) → placeholder ---------- */ + function exists(url) { return fetch(url, { method: 'HEAD', cache: 'no-store' }) - .then(function (r) { return r.ok ? url : PLACEHOLDER; }) - .catch(function () { return PLACEHOLDER; }); + .then(function (r) { return r.ok ? url : null; }) + .catch(function () { return null; }); + } + /* ไล่ลองนามสกุลทีละตัว (.jpg → .jpeg → .webp → .png) — ไม่มีเลย = null */ + function firstExisting(base) { + var i = 0; + function next() { + if (i >= IMG_EXTS.length) return Promise.resolve(null); + var url = base + '.' + IMG_EXTS[i++]; + return exists(url).then(function (u) { return u || next(); }); + } + return next(); + } + function resolveImage(stop) { + var sid = stop && stop.station_id; + var code = pad5(stop && stop.kilometer); + var chain = sid ? firstExisting(STATION_IMG_DIR + sid) : Promise.resolve(null); + return chain.then(function (u) { return u ? exists(u) : null; }) + .then(function (u) { + if (u) return u; + return code ? firstExisting(IMG_DIR + code) : null; + }) + .then(function (u) { return u || PLACEHOLDER; }); } /* ---------- KPI (คำนวณจากข้อมูลจริง) ---------- */ @@ -107,7 +127,7 @@ } /* ---------- การ์ดป้าย ---------- */ - function buildCard(stop, imgUrl, idx) { + function buildCard(stop, imgUrl, idx, routeIds) { var li = document.createElement('li'); li.setAttribute('data-idx', String(idx)); @@ -157,11 +177,17 @@ row.className = 'mu-chip-row'; // ★ สายรถประจำทางที่ผ่านป้ายนี้ (buses-line) + // สายที่มีใน routes.json → ทำเป็นลิงก์ไปหน้ารายละเอียดสายนั้น (#/routes/<รหัส>) var buses = stop['buses-line'] || []; if (buses.length) { buses.forEach(function (n) { - var b = document.createElement('span'); + var known = routeIds.indexOf(String(n)) !== -1; + var b = document.createElement(known ? 'a' : 'span'); b.className = 'mu-chip route'; + if (known) { + b.href = '#/routes/' + encodeURIComponent(n); + b.title = t('stops.viewRoute', { n: n }); + } b.textContent = t('stops.busPrefix') + ' ' + n; row.appendChild(b); }); @@ -193,44 +219,67 @@ return li; } - function renderStops(stops, host) { + /* ---------- สร้างการ์ดแบบทยอย (lazy) ---------- + - สร้าง "ทุกใบ" เป็น
  • เปล่า (มี data-idx) เพื่อให้ตัวกรอง/นับผลทำงานถูกต้องทันที + - โหลดรูป + เนื้อหา "เฉพาะใบที่มองเห็น" → เปิดหน้าเร็ว (ไม่ยิง 154 รูปพร้อมกัน) + - ใบที่ยังไม่โหลด: ใส่ที่กันที่ว่างชั่วคราว แล้วโหลดเมื่อถูกเรียก (แสดงทั้งหมด / ค้นหาเจอ) */ + var CARD_STUB = ''; + + function renderStops(stops, host, routeIds) { host.innerHTML = ''; if (!stops.length) { var empty = document.createElement('li'); empty.className = 'mu-stop-empty'; empty.textContent = t('stops.noResult'); host.appendChild(empty); - return; + return Promise.resolve(); } - // โหลดรูปทีละใบ แล้วค่อยต่อการ์ด (รักษาลำดับ) - var chain = Promise.resolve(); stops.forEach(function (stop, idx) { - chain = chain.then(function () { - return resolveImage(stop.kilometer).then(function (url) { - host.appendChild(buildCard(stop, url, idx)); - }); - }); + var li = document.createElement('li'); + li.setAttribute('data-idx', String(idx)); + li.innerHTML = CARD_STUB; + host.appendChild(li); }); - return chain; + if (window.StopsSearch && window.StopsSearch.apply) window.StopsSearch.apply(); /* ให้ตัวกรองนับ/แสดงผลทันที */ + return Promise.resolve(); } + /* โหลดเนื้อหาการ์ดจริงของใบนั้น (เรียกครั้งเดียวต่อใบ) */ + function hydrateCard(li, stops, routeIds) { + if (!li || li.getAttribute('data-loaded')) return Promise.resolve(); + var idx = parseInt(li.getAttribute('data-idx'), 10); + if (isNaN(idx) || !stops[idx]) return Promise.resolve(); + li.setAttribute('data-loaded', '1'); + return resolveImage(stops[idx]).then(function (url) { + var built = buildCard(stops[idx], url, idx, routeIds); /* buildCard คืน
  • ของมันเอง */ + li.innerHTML = ''; + while (built.firstChild) li.appendChild(built.firstChild); /* ย้ายเนื้อหาเข้ามา — ห้ามซ้อน
  • */ + }); + } + + var STATE = { stops: [], routeIds: [] }; /* ให้โมดูลอื่น (search) เรียก hydrateCard ได้ */ + /* ---------- init ---------- */ function init() { var host = document.getElementById('stops-list'); if (!host) return; - fetchJSON(DATA_URL).then(function (data) { + Promise.all([fetchJSON(DATA_URL), fetchJSON(ROUTES_URL)]).then(function (res) { + var data = res[0], routesDoc = res[1] || {}; var stops = Array.isArray(data) ? data : (data && data.stops) || []; + var routeIds = (routesDoc.routes || []).map(function (r) { return String(r.route_id); }); if (!stops.length) { host.innerHTML = '
  • ' + t('stops.noResult') + '
  • '; return; } renderKpi(stops); + STATE.stops = stops; + STATE.routeIds = routeIds; // ผูก event ก่อน render การ์ด — กันเคสที่ render ค้างแล้วปุ่มไม่ตอบสนอง if (window.StopsSearch) window.StopsSearch.init(stops); - renderStops(stops, host).then(function () { - // การ์ดพร้อมแล้ว → ให้ search module กรองซ้ำครั้งแรก + renderStops(stops, host, routeIds).then(function () { if (window.StopsSearch) window.StopsSearch.init(stops); + if (window.StopsSearch && window.StopsSearch.hydrateVisible) window.StopsSearch.hydrateVisible(); }); }); } @@ -242,5 +291,9 @@ } // เปิดให้ search module ใช้ helper ร่วมกัน - window.StopsRender = { pad5: pad5, PLACEHOLDER: PLACEHOLDER }; + window.StopsRender = { + pad5: pad5, + PLACEHOLDER: PLACEHOLDER, + hydrate: function (li) { return hydrateCard(li, STATE.stops, STATE.routeIds); } + }; })(); diff --git a/ui/partials/busStop.search.js b/ui/partials/busStop.search.js index 2cb39ee..b425648 100644 --- a/ui/partials/busStop.search.js +++ b/ui/partials/busStop.search.js @@ -19,6 +19,7 @@ stops: [], codeValue: '', placeQuery: '', + showAll: false, /* false = แสดง 6 ใบแรก · true = แสดงป้ายทั้งหมด */ bound: false }; @@ -36,6 +37,7 @@ ช่องที่ยังไม่กรอก → ถือเป็น 0 (เช่น "3" + "_" → "03+000") เก็บเป็น digits[] ความยาว 5 เสมอ */ + var PREVIEW_LIMIT = 6; /* แสดง 6 ใบแรก (กดปุ่มเพื่อดูทั้งหมด) */ var CODE_CELLS = 5; // 2 หน้า + 3 หลัง /* digits[] (5 หลัก) → "03+000" */ @@ -148,15 +150,19 @@ var f = currentFilter(); var filtered = state.stops.filter(function (s) { return f.fn(s, f.value); }); - // อัปเดตการ์ดที่มีอยู่แล้วใน DOM (ไม่ยิง network ซ้ำ) - var cards = host.querySelectorAll('li'); + /* จำกัด 6 ใบเมื่อ "ไม่ได้กรองอะไร" (เปิดหน้าปกติ) · ค้นหา/กรอง = แสดงผลทั้งหมดที่เจอ */ + var searching = !!f.value; + var limit = (searching || state.showAll) ? filtered.length : PREVIEW_LIMIT; + + var cards = [].filter.call(host.children, function (el) { return el.tagName === 'LI' && el.hasAttribute('data-idx'); }); var shown = 0; Array.prototype.forEach.call(cards, function (li) { var idx = parseInt(li.getAttribute('data-idx'), 10); if (isNaN(idx)) return; - var visible = filtered.indexOf(state.stops[idx]) !== -1; + var pos = filtered.indexOf(state.stops[idx]); + var visible = pos !== -1 && pos < limit; li.hidden = !visible; - if (visible) shown++; + if (visible) { shown++; if (window.StopsRender) window.StopsRender.hydrate(li); } /* โหลดรูปเฉพาะใบที่แสดง */ }); // empty state @@ -173,12 +179,29 @@ empty.hidden = true; } - // จำนวนผลลัพธ์ + // จำนวนผลลัพธ์ + ปุ่ม "แสดงป้ายทั้งหมด" var count = document.getElementById('stops-count'); if (count) { - count.textContent = t('stops.showing', { a: shown, b: state.stops.length }); + count.textContent = searching + ? t('stops.showing', { a: shown, b: filtered.length }) + : t('stops.showing', { a: shown, b: state.stops.length }); count.hidden = false; } + var more = document.getElementById('stops-show-all'); + if (more) { + var left = filtered.length - shown; + more.hidden = searching || state.showAll || left <= 0; /* กรองอยู่/แสดงครบแล้ว = ไม่ต้องมีปุ่ม */ + more.textContent = t('stops.showAll') + ' (' + filtered.length + ')'; + } + } + + /* โหลดเนื้อหาการ์ดของใบที่มองเห็น (เรียกหลัง render/กรอง) */ + function hydrateVisible() { + var host = document.getElementById('stops-list'); + if (!host) return; + [].forEach.call(host.children, function (li) { + if (li.tagName === 'LI' && li.hasAttribute('data-idx') && !li.hidden && window.StopsRender) window.StopsRender.hydrate(li); + }); } /* ---------- สลับโหมด (หัวใจของการกันชน) ---------- */ @@ -389,6 +412,16 @@ // ช่องรหัส: 6-box → เด้งช่อง + เติม 0 initCodeCells(); + // ปุ่ม "แสดงป้ายทั้งหมด" — กดแล้วเลิกจำกัด 6 ใบ (ไม่กรองอะไรอยู่) + var more = document.getElementById('stops-show-all'); + if (more) { + more.addEventListener('click', function () { + state.showAll = true; + apply(); + hydrateVisible(); + }); + } + // ช่องชื่อ: debounce + suggest if (placeInput) { var timer = null; @@ -399,6 +432,7 @@ state.placeQuery = v; renderSuggest(); apply(); + hydrateVisible(); }, 180); }); placeInput.addEventListener('focus', renderSuggest); @@ -423,6 +457,7 @@ var resetBtn = document.getElementById('stops-reset-btn'); if (resetBtn) { resetBtn.addEventListener('click', function () { + state.showAll = false; /* ล้างการค้นหา → กลับไปแสดง 6 ใบแรก */ var cells = codeCells(); Array.prototype.forEach.call(cells, function (c) { c.value = ''; }); if (placeInput) placeInput.value = ''; @@ -450,7 +485,7 @@ setMode(MODE_CODE); // เริ่มที่โหมดรหัส } - window.StopsSearch = { init: init, setMode: setMode, formatCode: formatCode }; + window.StopsSearch = { init: init, setMode: setMode, formatCode: formatCode , hydrateVisible: hydrateVisible }; // ให้ i18n เรียก render ใหม่ได้ (ไม่บังคับ) window.addEventListener('langchange', function () { diff --git a/ui/partials/checkSchedule.init.js b/ui/partials/checkSchedule.init.js index 85bc166..f4ed1a8 100644 --- a/ui/partials/checkSchedule.init.js +++ b/ui/partials/checkSchedule.init.js @@ -94,11 +94,16 @@ body.appendChild(none); } + /* มีอย่างน้อย 1 ทิศที่มีตารางจริงไหม — ถ้ามี ห้ามขึ้น "ยังไม่มีข้อมูล" ของทิศที่ว่าง + (จุดเดียวมีได้หลายทิศ · ทิศว่างไม่ควรทำให้การ์ดที่ตารางขึ้นแล้วดูเหมือนไม่มีข้อมูล) */ + var hasAny = g.recs.some(function (x) { return (x.departure_times || []).length > 0; }); + g.recs.forEach(function (r) { var times = (r.departure_times || []).slice(); - /* ไม่มีเวลาเลย (เช่น สาย 999: departure_times = []) → บอกว่าไม่มีข้อมูล ไม่ต้องมีบรรทัดลอย */ + /* ทิศนี้ยังไม่มีเวลา → ข้ามไปเลยถ้าทิศอื่นมีการ์ดข้อมูลอยู่แล้ว */ if (!times.length) { + if (hasAny) return; var empty = document.createElement('p'); empty.className = 'mu-stop-sub'; empty.textContent = t('route.empty'); @@ -106,15 +111,22 @@ return; } + /* หัวแถว = ชื่อทิศ (dir_label) → ไม่มีค่อยใช้ dir_note → ไม่มีอีกค่อยบอกว่าอยู่ที่จุดนี้ + ทิศที่ไปคนละทางจากจุดเดียวกัน (ป่าโมกไปอ่างทอง / ป่าโมกไปอยุธยา) จึงแยกให้เห็นชัด */ var sub = document.createElement('p'); sub.className = 'mu-stop-sub'; - sub.innerHTML = r.direction_note - ? esc(r.direction_note) + ' ' + esc(t('check.direction')) + '' - : esc(t('check.atStop')) + ' ' + esc(g.name); + if (r.dir_label) { + sub.innerHTML = esc(r.dir_label) + + (r.direction_note ? ' ' + esc(r.direction_note) + '' : ''); + } else if (r.direction_note) { + sub.innerHTML = esc(r.direction_note) + ' ' + esc(t('check.direction')) + ''; + } else { + sub.textContent = t('check.atStop') + ' ' + g.name; + } body.appendChild(sub); var grid = document.createElement('div'); - grid.className = 'mu-time-grid'; + grid.className = 'mu-time-grid' + (r.estimated ? ' is-est' : ''); /* เวลาที่คำนวณจากต้นทาง */ var chips = []; times.forEach(function (tm) { var c = document.createElement('div'); @@ -124,6 +136,18 @@ chips.push(c); }); body.appendChild(grid); + if (r.estimated) { + var est = document.createElement('p'); + est.className = 'mu-est-note'; + /* มาจากกฎ "จุดนี้ = เวลาจุดอ้างอิง ± n นาที" → บอกจุดอ้างอิง + เตือนเรื่องการจราจร */ + est.textContent = r.estimateFrom && window.Schedules.offsetLabel + ? t('time.derived', { + base: r.estimateFrom.name || ('#' + r.estimateFrom.station_id), + n: Schedules.offsetLabel(r.estimateFrom.offsetMin) + }) + : t('time.estimated'); + body.appendChild(est); + } sections.push({ chips: chips, times: times, station: g.name }); if (r.schedule_note) { @@ -188,11 +212,12 @@ Promise.all([ fetchJSON(DATA + 'routes.json'), fetchJSON(DATA + 'stations.json'), - fetchJSON(DATA + 'schedules.json') + Schedules.load().then(function (sd) { return Schedules.normSub(sd); }) ]).then(function (res) { var routes = (res[0] || {}).routes || []; var sts = (res[1] || {}).stations || []; - var recs = (res[2] || {}).schedules || res[2] || []; + if (window.Schedules && Schedules.setStationNames) Schedules.setStationNames(sts); /* ให้ข้อความ "คำนวณจาก ..." มีชื่อจุด */ + var recs = window.Schedules ? Schedules.records(res[2]) : ((res[2] || {}).schedules || res[2] || []); if (!routes.length) return; var route = routes.filter(function (r) { return String(r.route_id) === want; })[0] || @@ -225,6 +250,9 @@ /* จัดกลุ่มตามลำดับจุดจอดของสาย แล้วต่อด้วยจุดที่เหลือ (ถ้ามีข้อมูล) */ var order = (route.station_ids || []).slice(); + /* schema 2: ใช้ station_order ที่ตรวจทิศทางมาแล้วจากไฟล์ (ถ้ามี) */ + var sched = window.Schedules ? Schedules.route(res[2], rid) : null; + if (sched && sched.station_order.length) order = sched.station_order.slice(); recs.forEach(function (r) { if (String(r.route_id) === rid && order.indexOf(r.station_id) === -1) order.push(r.station_id); }); @@ -249,9 +277,28 @@ var desc = $('check-zone-desc'); if (desc) { var names = groups.map(function (g) { return g.name; }); + /* บอกว่า "ตารางวันนี้" เป็นของวันไหน — เฉพาะสายที่มีการแยกตารางตามวัน (service) เท่านั้น + สายอื่นข้อความเหมือนเดิมทุกตัวอักษร */ + /* ป้ายบอกว่า "ตารางที่เห็นอยู่นี้เป็นของวันไหน" — ใช้ผลตรวจวันจากตัวอ่านกลาง (ไม่คำนวณเองในหน้านี้) */ + var dayLine = ''; + if (window.Schedules && Schedules.dayInfo && Schedules.directions) { + var di = Schedules.dayInfo(); + var infos = (Schedules.directions(res[2], rid) || []).map(function (d) { return d.service || { from: 'ไม่ระบุ' }; }); + var conflict = infos.some(function (x) { return x.conflict; }); /* ทิศเดียวมีทั้งวันทำงาน+วันหยุด */ + var unknown = infos.some(function (x) { return x.unknown; }); /* ยังไม่ระบุวันเลย */ + var selectedByDay = infos.some(function (x) { return x.from === 'service' || x.from === 'ระบุตรง' || x.from === 'คำในโน้ต'; }); + if (unknown) { + dayLine = ' · ' + t('check.dayUnknown'); + } else if (conflict) { + dayLine = ' · ' + t('check.dayMixed'); + } else if (selectedByDay) { + dayLine = ' · ' + t(di.dayType === 'holiday' ? 'check.dayHoliday' : 'check.dayWeekday') + + ' (' + t('check.dayOfWeek') + ' ' + di.weekday_th + ')'; + } + } desc.textContent = 'สาย ' + rid + ' · ' + (names.length > 1 ? names[0] + ' \u2192 ' + names[names.length - 1] + ' · ' : '') + - groups.length + ' ' + t('check.stopsCount'); + groups.length + ' ' + t('check.stopsCount') + dayLine; } /* KPI */ diff --git a/ui/partials/credits.html b/ui/partials/credits.html index f6d1631..0ed8c42 100644 --- a/ui/partials/credits.html +++ b/ui/partials/credits.html @@ -51,57 +51,10 @@

    ใบอนุญาต: Leaflet BSD-2-Clause · ชุดแผนที่ (tiles): OpenStreetMap © ผู้มีส่วนร่วม (ODbL)

    • Leaflet — ไลบรารีแผนที่แบบ open-source
    • -
    • OpenStreetMap — ข้อมูลแผนที่และภาพ tiles
    • -
    • ในเวอร์ชัน mockup นี้ใช้ภาพแผนที่จำลอง (mock map) เพื่อการแสดงผลก่อนเชื่อมต่อข้อมูลจริง
    • +
    • OpenStreetMap — ภาพ tiles และข้อมูลแผนที่ที่ใช้แสดงผล
    • +
    • เส้นทางเดินรถ จุดจอด และหมุดสถานี วาดจากข้อมูล GIS ของทีม (GeoJSON) ทับบนแผนที่
    -
    -

    รูปภาพประกอบ

    -

    โฟลเดอร์ .image/ — ภาพตัวอย่าง (placeholder) สำหรับพัฒนา mockup

    -
      -
    • ภาพเส้นทาง/รถ (routes/) — ภาพตัวอย่างสำหรับแสดงการ์ดสายรถ รอแทนที่ด้วยภาพจริง
    • -
    • ภาพจุดสังเกต (landmarks/) — วัด ตลาด ริมน้ำ ฯลฯ ใช้เป็นภาพตัวอย่าง
    • -
    • ภาพแผนที่เครือข่าย (network/overview-map.png) — แผนที่ตัวอย่าง
    • -
    • QR code (qrcode/) — รหัส QR ของสายรถแต่ละสาย
    • -
    • โลโก้ minibus (icons/) — โลโก้และ favicon ของเว็บ
    • -
    • maintheme.png — ภาพดีไซน์ต้นแบบ (theme reference) ของโปรเจกต์
    • -
    -
    - -
    -

    โลโก้ผู้สนับสนุนและพาร์ทเนอร์

    -

    โฟลเดอร์ .image/partners/ — โลโก้เป็นเครื่องหมายการค้าของบริษัทเจ้าของแต่ละราย

    -
      -
    • 7-Eleven, Shopee, Lazada, airasia MOVE, busonlineticket, Trip.com, truck2hand, ทีซีแอล 999 อ่างทอง, รถบัสปิ่นเกล้า
    • -
    • โลโก้เหล่านี้ใช้เพื่อแสดงรายชื่อผู้สนับสนุน/พันธมิตรเท่านั้น สิทธิ์ทั้งหมดเป็นของเจ้าของ
    • -
    -
    - -
    -

    ข้อมูลการเดินรถ

    -
      -
    • ข้อมูลเส้นทาง ตารางเวลา และจุดจอด อ้างอิงจากข้อมูลผู้ประกอบการรถโดยสารและสถานีขนส่งผู้โดยสาร (บขส.)
    • -
    • ข้อมูลใน mockup นี้เป็น ข้อมูลตัวอย่าง (resource/data/*.json) สำหรับการพัฒนา — ยังไม่ใช่ข้อมูลจริงที่อัปเดตล่าสุด
    • -
    -
    - -
    -

    โหมดออฟไลน์ (PWA / Service Worker)

    -

    พัฒนาโดยทีม Atroute — ไม่ใช้ไลบรารีภายนอก

    -
      -
    • เว็บนี้เป็น Progressive Web App — ติดตั้งได้ (Add to Home Screen) และเปิดใช้งานได้เมื่อไม่มีอินเทอร์เน็ต
    • -
    • อัปเดตเนื้อหาอัตโนมัติ: เมื่อเปิดเว็บ ระบบจะตรวจสอบเวอร์ชันใหม่และโหลดให้เอง — ผู้ใช้ไม่ต้องล้างแคช
    • -
    • ไฟล์ที่เกี่ยวข้อง: ui/sw.js, ui/pwa.js, ui/manifest.json
    • -
    -
    - -
    -

    หมายเหตุ

    -
      -
    • เว็บนี้เป็นต้นแบบ (prototype) สำหรับพัฒนาเว็บข้อมูลการเดินรถของสถานีขนส่งผู้โดยสารจังหวัดอ่างทอง
    • -
    • หากใช้ทรัพยากรใดผิดข้อกำหนดของเจ้าของ กรุณาแจ้งทีมพัฒนาเพื่อแก้ไขทันที
    • -
    -
    diff --git a/ui/partials/home.init.js b/ui/partials/home.init.js index ec27408..ccae008 100644 --- a/ui/partials/home.init.js +++ b/ui/partials/home.init.js @@ -86,12 +86,6 @@ stationSelect.innerHTML = ''; var list = stationsFor(provinceId); - /* ตัวเลือกแรก = ทุกสถานีในจังหวัด (ค่าเริ่มต้น → แสดงทุกสาย) */ - var all = document.createElement('option'); - all.value = ''; - all.textContent = tr('home.allStations'); - stationSelect.appendChild(all); - list.forEach(function (st) { var opt = document.createElement('option'); opt.value = st.station_code; /* ใช้รหัสสถานี = ลิงก์สั้น อ่านง่าย */ @@ -100,8 +94,11 @@ }); if (!list.length) { - all.textContent = tr('home.stationEmpty'); - all.disabled = true; + var none = document.createElement('option'); /* ไม่มีสถานีในจังหวัดนี้ → บอกด้วยตัวเลือกว่าง */ + none.value = ''; + none.textContent = tr('home.stationEmpty'); + none.disabled = true; + stationSelect.appendChild(none); if (stationHint) stationHint.textContent = tr('home.stationEmptyHint') + ' ' + provinceName(provinceId); } else if (stationHint) { stationHint.innerHTML = tr('home.stationCount', { n: list.length }) + ' ' + provinceName(provinceId); @@ -109,7 +106,9 @@ /* คืนค่าที่เลือกไว้ (จากลิงก์) ถ้ามีในจังหวัดนี้ */ if (preferredCode && list.some(function (s) { return s.station_code === preferredCode; })) { - stationSelect.value = preferredCode; + stationSelect.value = preferredCode; /* จากลิงก์แชร์ (?s=) */ + } else if (list.length) { + stationSelect.value = list[0].station_code; /* ไม่มีตัวเลือก "ทุกสถานี" แล้ว → เลือกสถานีแรก */ } else { stationSelect.value = ''; } @@ -200,12 +199,12 @@ fetchJSON(DATA_URL.routeGroups), fetchJSON(DATA_URL.routes), fetchJSON(DATA_URL.routesMunicipal), - fetchJSON(DATA_URL.schedules) + (window.Schedules ? Schedules.load().then(function (sd) { return Schedules.normSub(sd); }) : fetchJSON(DATA_URL.schedules)) ]).then(function (res) { var groups = ((res[0] || {}).route_groups) || []; var routes = ((res[1] || {}).routes) || []; var municipal = ((res[2] || {}).routes) || []; - var recs = (res[3] || {}).schedules || res[3] || []; + var recs = window.Schedules ? Schedules.records(res[3]) : ((res[3] || {}).schedules || res[3] || []); if (!groups.length || !routes.length) return; /* รวมเส้นทางหมวดเทศบาลจากไฟล์แยก (ข้ามแถวที่ยังไม่ได้กรอก) */ diff --git a/ui/partials/otherStop.js b/ui/partials/otherStop.js new file mode 100644 index 0000000..7cc1df6 --- /dev/null +++ b/ui/partials/otherStop.js @@ -0,0 +1,151 @@ +/* ============================================================ + otherStop.js — ตัวอ่าน '8 other_stop.json' (ใช้ร่วมทุกหน้า) + + ทำไมต้องมี: จุดจอด station_id 8 คือ "จุดขึ้นรถประจำทางอื่นๆ" ซึ่งเป็นชื่อรวม ๆ + ของทุกสาย — ตัวจริงของแต่ละสายอยู่ใน '8 other_stop.json' เช่น + + { "route_id": "1101", "station_name_th": "วัดสีบัวทอง", ... } ← 1101 คือสาย 1011 + + ไฟล์นี้จึงต้อง "จับคู่ route id" ก่อน แล้วค่อยเอาชื่อ/พิกัดจริงของสายนั้นไปแสดง + (เช่น หน้าป้ายต้องขึ้น "จุดขึ้นรถประจำทางอื่นๆ · วัดสีบัวทอง") + + API: + OtherStop.load() → Promise (โหลดครั้งเดียวแล้ว cache) + OtherStop.fileRouteId(entry) → รหัสสายตามที่เขียนในไฟล์ + OtherStop.resolve(fileRouteId, validIds) → { id, alias } | null + OtherStop.forRoute(entries, routeId, validIds) → entry | null + OtherStop.forStation(entries, station, routeId, validIds) → entry | null + OtherStop.stopsOf(entry) → [{ name, lat, lng, hasCoord, city_th, province_th, index }] + OtherStop.firstName(entry) → ชื่อจุดแรก (ใช้เป็นชื่อย่อของสาย) + OtherStop.allStops(entries, routeId, validIds) → รายการจุดจริง "ทุกจุด" ของสายนั้น + · แต่ละจุดมี offsetMin = นาทีจากจุดแรก (ถ้าไฟล์ใส่ "offsets_min") → ใช้คำนวณเวลาของจุดนั้นได้ + · ฟิลด์ในไฟล์: station_name_th[], latitude[], longitude[], offsets_min[] (จับคู่ตามลำดับ) + ============================================================ */ +(function () { + 'use strict'; + + var URL = '../resource/data/8%20other_stop.json'; + var cache = null; + + /* โหลดครั้งเดียว — คืน promise เดิมซ้ำ (ไม่ยิง fetch ซ้ำทุกหน้า) */ + function load() { + if (cache) return cache; + cache = fetch(URL, { cache: 'no-store' }) + .then(function (r) { return r.ok ? r.json() : null; }) + .then(function (d) { return (d && d.other_stop) || []; }) + .catch(function () { return []; }); + return cache; + } + + function fileRouteId(entry) { + return String((entry && entry.route_id) != null ? entry.route_id : ''); + } + + /* เทียบรหัสสายแบบ "ทนรหัสเพี้ยน": 1101 → 1011 (ตัวเลขชุดเดียวกัน สลับตำแหน่ง) + ใช้เฉพาะเมื่อรหัสในไฟล์ "ไม่มีจริง" ใน routes.json และหาคู่ได้ไม่กำกวม (1 ตัวเท่านั้น) */ + function sameDigits(a, b) { + var na = String(a).replace(/\D/g, ''), nb = String(b).replace(/\D/g, ''); + if (!na || na.length !== nb.length) return false; + return na.split('').sort().join('') === nb.split('').sort().join(''); + } + + function resolve(fid, validIds) { + var want = String(fid); + var valid = (validIds || []).map(String); + if (valid.indexOf(want) !== -1) return { id: want, alias: false }; + /* เทียบแบบสลับตำแหน่ง (1101 → 1011) เฉพาะรหัสยาว ≥3 หลัก + — รหัสสั้นอย่าง "51"/"15" มีโอกาสสลับกันได้จริง → ไม่เดา */ + var digits = want.replace(/\D/g, ''); + if (digits.length < 3) return null; + var cands = valid.filter(function (v) { return sameDigits(v, want); }); + if (cands.length === 1) return { id: cands[0], alias: true }; + return null; /* ไม่รู้จัก หรือกำกวม → ไม่เดา */ + } + + function forRoute(entries, routeId, validIds) { + var want = String(routeId); + var hit = (entries || []).filter(function (e) { return fileRouteId(e) === want; })[0]; + if (hit) return hit; + /* ถ้ายังไม่เจอ → หา entry ที่รหัสในไฟล์หมายถึงสายนี้ (เช่น 1101 → 1011) */ + var found = null; + (entries || []).forEach(function (e) { + if (found) return; + var r = resolve(fileRouteId(e), validIds); + if (r && r.id === want) found = e; + }); + return found; + } + + /* ทุก entry ที่หมายถึงสายนี้ (สายเดียวมีได้หลายจุดจริง) */ + function forRouteAll(entries, routeId, validIds) { + var want = String(routeId); + return (entries || []).filter(function (e) { + if (fileRouteId(e) === want) return true; + var r = resolve(fileRouteId(e), validIds); + return !!(r && r.id === want); + }); + } + + + /* ---------- แตก entry → รายการ "จุดจริง" ของสายนั้น ---------- + กติกาข้อมูล (เจ้าของข้อมูลกำหนด): + · station_name_th เป็นได้ทั้งข้อความเดียว หรือรายการหลายชื่อ (เช่น 954 = 4 จุด) + · latitude/longitude เป็นได้ทั้งตัวเลขเดียว หรือรายการ — จับคู่กับชื่อ "ตามลำดับ" + · "พิกัดเป็นของชื่อแรก" → ถ้ามีพิกัดเดียว ชื่อที่ 2 เป็นต้นไป = ยังไม่มีพิกัด (ไม่เดา) */ + function num(v) { var n = parseFloat(v); return isNaN(n) ? null : n; } + function stopsOf(entry) { + if (!entry) return []; + var names = [].concat(entry.station_name_th == null ? [] : entry.station_name_th) + .map(function (x) { return String(x == null ? '' : x).trim(); }) + .filter(Boolean); + var lats = [].concat(entry.latitude == null ? [] : entry.latitude); + var lngs = [].concat(entry.longitude == null ? [] : entry.longitude); + var offs = [].concat(entry.offsets_min == null ? [] : entry.offsets_min); /* นาทีจากจุดแรก (0 = จุดแรกเอง) */ + return names.map(function (name, i) { + var lat = num(lats[i]), lng = num(lngs[i]); + return { + index: i, + name: name, + /* city/province ในไฟล์อธิบาย "จุดแรก" — จุดอื่นไม่ทราบ ไม่เดา */ + city_th: i === 0 ? (entry.city_th || null) : null, + province_th: i === 0 ? (entry.province_th || null) : null, + station_type: entry.station_type || null, + note: entry.note || null, + lat: lat, lng: lng, + offsetMin: num(offs[i]), /* ระยะเวลาจากจุดแรก (นาที) — ไม่ใส่ = ไม่ทราบ */ + hasCoord: lat != null && lng != null, + entry: entry + }; + }); + } + function firstName(entry) { var st = stopsOf(entry)[0]; return st ? st.name : null; } + function allStops(entries, routeId, validIds) { + var out = []; + forRouteAll(entries, routeId, validIds).forEach(function (e) { out = out.concat(stopsOf(e)); }); + return out; + } + + /* ใช้กับ "สถานี 8" (จุดขึ้นรถประจำทางอื่นๆ) เท่านั้น */ + function isOtherStop(station) { + if (!station) return false; + return String(station.station_code) === 'other_stop' || Number(station.station_id) === 8; + } + + function forStation(entries, station, routeId, validIds) { + if (!isOtherStop(station)) return null; + return forRoute(entries, routeId, validIds); + } + + window.OtherStop = { + load: load, + fileRouteId: fileRouteId, + resolve: resolve, + forRoute: forRoute, + forRouteAll: forRouteAll, + isOtherStop: isOtherStop, + forStation: forStation, + stopsOf: stopsOf, + firstName: firstName, + allStops: allStops + }; +})(); diff --git a/ui/partials/schedules.js b/ui/partials/schedules.js new file mode 100644 index 0000000..033739b --- /dev/null +++ b/ui/partials/schedules.js @@ -0,0 +1,618 @@ +/* ============================================================ + schedules.js — ตัวอ่านข้อมูลตารางเวลา (ใช้ร่วมทุกหน้า) + + ***APIs นี้ไม่เปลี่ยนชื่อ/รูปเดิม*** — หน้า check/busDetail/home/stopDetail เรียกเหมือนเดิม + ที่เพิ่มเข้ามาคือ "สมองเรื่องวันทำงาน/วันหยุด" ซึ่งทำงานอยู่ในไฟล์นี้ที่เดียว + + รองรับ schedules.json 2 รูปแบบ: + schema 1 (เดิม): { "schedules": [ { route_id, station_id, direction_note, departure_times[], schedule_note } ] } + schema 2 (ใหม่): { "schema": 2, "routes": [ { route_id, station_order[], directions: [ + { dir_id, dir_label, service?, stops: [ { station_id, times[], dir_note?, note?, groups? } ] } ] } ] } + + ── เรื่องวันทำงาน / วันหยุด (ไม่ต้องแก้โค้ดหน้าไหนเลย) ──────────────── + เพิ่มฟิลด์ "ไม่บังคับ" 2 ระดับ: + 1) ระดับทิศทาง: "service": "all" | "weekday" | "holiday" + - ทั้งทิศทางใช้เฉพาะวันนั้น (เช่น ทิศ 'ตารางวันหยุด' → service: "holiday") + - ไม่ใส่ = "all" (ทุกวัน) → ไฟล์เดิมไม่ต้องแก้อะไร พฤติกรรมเหมือนเดิมเป๊ะ + 2) ระดับจุดจอด: "groups": [ { "label": "วันหยุด", "dayType": "holiday", "times": ["10:00"] } ] + - เวลาที่ "เพิ่มเข้ามาเฉพาะบางวัน" (ตรงกับโน้ตเดิม เช่น "10:00 มีเฉพาะวันหยุด") + - times[] ยังเป็นตารางพื้นฐานที่ใช้ทุกวัน + + ค่าเริ่มต้น: ตรวจจากวันที่ของเครื่องเอง (เสาร์–อาทิตย์ = วันหยุด + วันนักขัตฤกษ์จาก holidays.json) + ความปลอดภัย: ถ้ากรองตามวันแล้วไม่เหลือทิศทางใดเลย → ถอยไปใช้ทั้งหมด + ติดธง fallback (หน้าเว็บไม่ว่าง) + + API: + Schedules.records(doc, opts) → record แบน (schema เดิม) สำหรับโค้ดเดิม + Schedules.route(doc, routeId, opts) → { route_id, station_order[], directions[], entries[] } + Schedules.directions(doc, routeId, opts) → [{ dir_id, dir_label, service, dayType, fallback, stops[] }] + Schedules.times(doc, routeId, opts) → เวลาทั้งหมดของสาย (เรียงแล้ว) + Schedules.countTrips(doc, routeId, opts) → จำนวนเที่ยวของสาย + Schedules.todayType() → 'weekday' | 'holiday' + Schedules.dayInfo(date) → { dayType, label_th, date } + Schedules.ready → promise (โหลด holidays.json เสร็จ) + opts ที่รับได้: { dayType: 'all' | 'weekday' | 'holiday' } (ไม่ส่ง = ตรวจจากวันนี้) + ============================================================ */ +(function () { + 'use strict'; + + var DATA_URL = '../resource/data/'; + var HOLIDAYS = []; + var ALIAS = { weekend: 'holiday', 'sat-sun': 'holiday', saturday: 'holiday', sunday: 'holiday', workday: 'weekday', weekday: 'weekday', holiday: 'holiday', all: 'all' }; + + /* ความเร็วเฉลี่ยตั้งต้นสำหรับคำนวณเวลาจุดที่ไม่มีตาราง (ปรับต่อทิศได้ด้วย "speedKmh") */ + var DEFAULT_SPEED_KMH = 40; + + function pad2(n) { return (n < 10 ? '0' : '') + n; } + function toMin(hhmm) { + var a = String(hhmm).split(':'); + var h = parseInt(a[0], 10), m = parseInt(a[1], 10); + return (isNaN(h) ? 0 : h) * 60 + (isNaN(m) ? 0 : m); + } + + /* คำนวณเวลาของจุดที่ไม่มีตาราง จากจุดที่มีเวลาแล้วซึ่งอยู่ใกล้ที่สุดตามระยะทาง (กม.) + คืน null เมื่อคำนวณไม่ได้ (ไม่มี กม. หรือไม่มีจุดอ้างอิง) */ + function computeTimes(stop, siblings, opts) { + var o = (typeof opts === 'number') ? { speedKmh: opts } : (opts || {}); + var speed = Number(o.speedKmh) > 0 ? Number(o.speedKmh) : DEFAULT_SPEED_KMH; + if (!stop || typeof stop.km !== 'number') return null; + var cands = siblings.filter(function (s) { + return s !== stop && typeof s.km === 'number' && (s.times || []).length; + }); + if (!cands.length) return null; + var base = null; + if (o.baseSid != null) { /* ผู้ใช้เลือกจุดอ้างอิงเอง (จากเครื่องมือแก้ไข) */ + base = cands.filter(function (s) { return String(s.station_id) === String(o.baseSid); })[0] || null; + } + if (!base && o.baseEnd === 'first') { /* ใช้เวลาจริงจากจุดต้นทาง (กม. น้อยสุด) */ + base = cands.reduce(function (a, b) { return a.km <= b.km ? a : b; }); + } else if (!base && o.baseEnd === 'last') { /* ใช้เวลาจริงจากจุดปลายทาง (กม. มากสุด) */ + base = cands.reduce(function (a, b) { return a.km >= b.km ? a : b; }); + } else if (!base) { /* อัตโนมัติ: จุดที่มีเวลาซึ่งใกล้ที่สุด */ + base = cands.reduce(function (a, b) { return Math.abs(b.km - stop.km) < Math.abs(a.km - stop.km) ? b : a; }); + } + var delta = (stop.km - base.km) / speed * 60; /* นาที (+ ไปข้างหน้า, - ย้อนหลัง) */ + return base.times.map(function (t) { + var tot = Math.round(toMin(t) + delta); + tot = ((tot % 1440) + 1440) % 1440; + return pad2(Math.floor(tot / 60)) + ':' + pad2(tot % 60); + }); + } + + /* ความเร็วที่ใช้จริงของทิศหนึ่ง ๆ: มาจาก travelMin (เวลาเดินทางทั้งเส้น) ถ้ามี ไม่งั้นใช้ speedKmh/ค่าตั้งต้น */ + function speedOf(dir) { + if (Number(dir.travelMin) > 0) { + var kms = (dir.stops || []).map(function (s) { return s.km; }).filter(function (x) { return typeof x === 'number'; }); + if (kms.length > 1) { + var span = Math.max.apply(null, kms) - Math.min.apply(null, kms); + if (span > 0) return { kmh: span / Number(dir.travelMin) * 60, span: span, source: 'travelMin' }; + } + } + return { kmh: Number(dir.speedKmh) > 0 ? Number(dir.speedKmh) : DEFAULT_SPEED_KMH, span: null, source: 'speedKmh' }; + } + + function hasSchema2(doc) { + return !!(doc && doc.schema === 2 && Array.isArray(doc.routes)); + } + function normSub(doc) { /* เตรียมไฟล์ย่อยให้อยู่ในรูป { routes: [...] } */ + if (!doc) return null; + if (doc.route_id != null && !Array.isArray(doc.routes)) { + var dirs = isSchema3(doc) ? directionsFromSchema3(doc) : (doc.directions || []); + return { schema: 2, routes: [{ route_id: doc.route_id, station_order: doc.station_order || [], directions: dirs }] }; + } + return doc; + } + + /* ---------- schema 3: { weekday:{directions:{...}}, holiday:{directions:{...}} } ---------- + โครงอ่านง่ายสำหรับเจ้าของข้อมูล (กลุ่มวัน → ทิศทาง) · แปลงเป็นทิศภายในให้ทุกหน้าใช้ต่อได้เหมือนเดิม + กติกา: จุดที่ระบุเวลามา = จุดตั้งต้นของทิศนั้น · จุดอื่นใน station_order คำนวณจาก กม.+ความเร็ว (ถ้าเปิด autoTimes) */ + var DAYGROUP = { weekday: 'weekday', holiday: 'holiday' }; + function isSchema3(doc) { return !!(doc && doc.schema === 3 && (doc.weekday || doc.holiday)); } + function directionsFromSchema3(doc) { + var out = []; + ['weekday', 'holiday'].forEach(function (kind) { + var grp = doc[kind]; + if (!grp || !grp.directions) return; + Object.keys(grp.directions).forEach(function (name) { + var src = grp.directions[name] || {}; + var times = (src.departures || src.times || []).slice(); + var from = (src.from_station_id != null) ? Number(src.from_station_id) : null; + var stops = []; + if (from != null && times.length) { + stops.push({ station_id: from, times: times, dir_note: grp.label || null }); + } else if (from != null) { + stops.push({ station_id: from, times: [], dir_note: grp.label || null }); + } + out.push({ + dir_id: kind + ':' + name, + dir_label: name, + service: { day: kind, from: 'schema 3', matches: kind === todayType() }, + station_order: doc.station_order || [], + stops: stops, + /* จุดตั้งต้นมีเวลาแล้ว → ให้จุดอื่นคำนวณต่อจาก กม. เฉพาะเมื่อเปิด autoTimes */ + autoTimes: !!doc.autoTimes + }); + }); + }); + return out; + } + + /* ---------- ชื่อจุดจอด (สำหรับข้อความ "คำนวณจาก ...") ---------- + โหลดเบื้องหลังครั้งเดียว — ถ้ายังไม่ทัน ก็ถอยไปใช้รหัสจุดในข้อความ (ไม่พัง) */ + var STATION_NAMES = {}; + var namesWarmed = false; + function warmStations() { + if (namesWarmed) return; + namesWarmed = true; + fetch(DATA_URL + 'stations.json', { cache: 'no-store' }) + .then(function (r) { return r.ok ? r.json() : null; }) + .then(function (d) { + ((d && d.stations) || []).forEach(function (st) { STATION_NAMES[String(st.station_id)] = st.station_name_th; }); + }) + .catch(function () {}); + } + function stationNameOf(id) { return STATION_NAMES[String(id)] || null; } + /* หน้าเว็บที่โหลด stations.json อยู่แล้วส่งชื่อเข้ามาได้ → ข้อความหมายเหตุมีชื่อทันที (ไม่ต้องรอ fetch) */ + function setStationNames(list) { + ((list && list.stations) || list || []).forEach(function (st) { + if (st && st.station_id != null) STATION_NAMES[String(st.station_id)] = st.station_name_th; + }); + } + /* เรียกทันทีตอนไฟล์ถูกโหลด — จะทันรอบเรนเดอร์แรก (ชื่อจุดอ้างอิงในข้อความ "คำนวณจาก ...") */ + warmStations(); + + /* ---------- เลื่อนเวลาเป็นนาที (กฎ derive: จุดนี้ = เวลาจุดอ้างอิง ± offset) ---------- + คืน HH:MM เรียงใหม่ · เกินเที่ยงคืน = วนกลับ (ไม่พัง) */ + function shiftTimes(times, offsetMin) { + var off = Number(offsetMin) || 0; + return (times || []).map(function (t) { + var a = String(t).split(':'); + var m = (parseInt(a[0], 10) || 0) * 60 + (parseInt(a[1], 10) || 0) + off; + m = ((m % 1440) + 1440) % 1440; + var hh = Math.floor(m / 60), mm = m % 60; + return (hh < 10 ? '0' : '') + hh + ':' + (mm < 10 ? '0' : '') + mm; + }).sort(); + } + /* ป้ายผลต่างเวลา เช่น +30 / −15 (ใช้ในข้อความหมายเหตุ) */ + function offsetLabel(min) { + var n = Number(min) || 0; + var sign = n < 0 ? '\u2212' : '+'; + return sign + Math.abs(n); + } + + /* ---------- เครื่องยนต์ตรวจวัน (จันทร์–อาทิตย์) ---------- + ทำงานที่ท่อกลางนี้ที่เดียว → ทุกหน้าได้ผลเหมือนกัน ไม่ต้องแก้โค้ดหน้าไหน + ลำดับการตัดสิน: + 1) ถ้าทิศมี "days" ระบุตรง ๆ (อา จ อ พ พฤ ศ ส) → ใช้ตามนั้น (แม่นสุด) + 2) ถ้ามี service = weekday/holiday → เทียบกับวันนี้ + 3) ถ้าไม่มีอะไรระบุ → อ่านคำใน dir_label / dir_note / note ของสายนั้น (ตรวจคำอัตโนมัติ) + 4) ตัดสินไม่ได้ → แสดงทุกวัน (ไม่ซ่อนข้อมูล) พร้อมป้ายว่า "ยังไม่ระบุวัน" */ + var DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; /* ตรงกับ Date.getDay() */ + var DAY_TH = { sun: 'อาทิตย์', mon: 'จันทร์', tue: 'อังคาร', wed: 'พุธ', thu: 'พฤหัสบดี', fri: 'ศุกร์', sat: 'เสาร์' }; + var DAY_ABBR = { sun: 'อา', mon: 'จ', tue: 'อ', wed: 'พ', thu: 'พฤ', fri: 'ศ', sat: 'ส' }; + var DAY_ALIAS = { /* รับได้หลายชื่อ */ + weekday: 'weekday', workday: 'weekday', 'วันทำงาน': 'weekday', 'จ-ศ': 'weekday', 'จ–ศ': 'weekday', + holiday: 'holiday', weekend: 'holiday', 'วันหยุด': 'holiday', 'ส-อา': 'holiday', 'ส–อา': 'holiday', 'เสาร์-อาทิตย์': 'holiday', + all: 'all', ทุกวัน: 'all', daily: 'all' + }; + var DAY_WORDS_HOLIDAY = ['วันหยุด', 'นักขัตฤกษ์', 'เสาร์-อาทิตย์', 'เสาร์–อาทิตย์', 'ส-อา', 'ส–อา', 'weekend', 'holiday']; + var DAY_WORDS_WEEKDAY = ['วันทำงาน', 'วันธรรมดา', 'จ-ศ', 'จ–ศ', 'จันทร์ถึงศุกร์', 'weekday', 'workday']; + + function ymd(d) { + var m = d.getMonth() + 1, day = d.getDate(); + return d.getFullYear() + '-' + (m < 10 ? '0' : '') + m + '-' + (day < 10 ? '0' : '') + day; + } + function dayKey(date) { return DAYS[(date || new Date()).getDay()]; } + function isHolidayDate(date, list) { + var list_ = list || HOLIDAYS; + if (list_.indexOf(ymd(date)) !== -1) return true; /* นักขัตฤกษ์ */ + var wd = (date.getDay() + 6) % 7; /* 0 = จันทร์ */ + return wd >= 5; /* เสาร์–อาทิตย์ = วันหยุด */ + } + function dayTypeOf(date, list) { return isHolidayDate(date || new Date(), list) ? 'holiday' : 'weekday'; } + function todayType(date) { return dayTypeOf(date); } + function dayInfo(date) { + var d = date || new Date(); + var t = dayTypeOf(d); + return { dayType: t, weekday: DAYS[d.getDay()], weekday_th: DAY_TH[DAYS[d.getDay()]], date: ymd(d), + label_th: t === 'holiday' ? 'วันหยุด (ส–อา/นักขัตฤกษ์)' : 'วันทำงาน (จ–ศ)' }; + } + /* ตรวจคำในข้อความ (dir_label / dir_note / note) ว่าหมายถึงวันไหน */ + function detectDay(text) { + var t = String(text == null ? '' : text).trim(); + if (!t) return null; + var low = t.toLowerCase(); + var hitH = DAY_WORDS_HOLIDAY.filter(function (w) { return low.indexOf(w.toLowerCase()) !== -1; })[0]; + var hitW = DAY_WORDS_WEEKDAY.filter(function (w) { return low.indexOf(w.toLowerCase()) !== -1; })[0]; + if (hitH && !hitW) return { day: 'holiday', from: 'คำ', text: t }; + if (hitW && !hitH) return { day: 'weekday', from: 'คำ', text: t }; + return null; /* เจอทั้งคู่/ไม่เจอ = ไม่เดา */ + } + /* รวบข้อความทั้งหมดของทิศ (label + โน้ตของทุกจุด) แล้วตรวจหา "วัน" ให้สอดคล้องกันทั้งทิศ + คืน { day, from, text } หรือ null (ยังไม่ระบุ) */ + function detectDayOfDir(d) { + var texts = []; + if (d && d.dir_label) texts.push(d.dir_label); + ((d && d.stops) || []).forEach(function (s) { + if (s.dir_note) texts.push(s.dir_note); + if (s.note) texts.push(s.note); + }); + var verdicts = [], conflicts = false, hasHol = false, hasWk = false, sample = null; + texts.forEach(function (t) { + var v = detectDay(t); + if (!v) { return; } + if (v.day === 'holiday') { hasHol = true; } else { hasWk = true; } + verdicts.push(v); if (!sample) sample = v; + }); + if (!verdicts.length) return null; + if (hasHol && hasWk) { /* ทิศเดียวมีทั้งสองวัน */ + return { day: 'all', from: 'ปนกัน', text: sample.text, conflict: true }; + } + return { day: verdicts[0].day, from: 'คำในโน้ต', text: sample.text }; + } + /* วันนี้ตรงกับทิศนี้ไหม + บอกเหตุผล (ใช้แสดงบนหน้าเว็บได้) */ + function serviceOf(obj, dirForDetect) { + if (obj && obj.days && obj.days.length) { /* ระบุวันตรง ๆ มาก่อน */ + return { day: 'custom', days: obj.days.map(String), from: 'ระบุตรง', matches: obj.days.map(String).indexOf(dayKey()) !== -1 }; + } + var s = (obj && obj.service) ? String(obj.service).toLowerCase() : ''; + var alias = DAY_ALIAS[s] || (DAY_ALIAS[String(obj && obj.service)] || ''); + if (alias === 'weekday' || alias === 'holiday') { + return { day: alias, from: 'service', matches: alias === todayType() }; + } + if (alias === 'all') return { day: 'all', from: 'service', matches: true }; + var det = detectDayOfDir(dirForDetect || obj); /* ไม่ระบุ → ตรวจจากคำ */ + if (det) { + if (det.day === 'all') return { day: 'all', from: det.from + ' (ปนกัน)', text: det.text, conflict: true, matches: true }; + return { day: det.day, from: det.from, text: det.text, matches: det.day === todayType() }; + } + return { day: 'all', from: 'ไม่ระบุ', unknown: true, matches: true }; /* ไม่รู้ = แสดง (ไม่ซ่อนข้อมูล) */ + } + function normDay(opts) { + if (opts && opts.dayType) return DAY_ALIAS[String(opts.dayType).toLowerCase()] || 'all'; + return todayType(); + } + + /* ตัดสินว่าทิศนี้ใช้กับวันที่กำลังดูอยู่ไหม + service = ผลจาก serviceOf() → { day, matches, conflict?, unknown? } */ + function applies(info, day) { + if (!day || day === 'all') return true; /* ไม่ระบุวัน = ดูทุกวัน */ + if (!info || typeof info !== 'object') return true; + if (info.unknown) return true; /* ยังไม่ระบุวัน → แสดง (ไม่ซ่อนข้อมูล) */ + if (info.conflict) return true; /* ทิศเดียวมีทั้ง 2 ตาราง → ซ่อนไม่ได้ (จะหายข้อมูล) */ + if (info.day === 'custom') { /* ระบุวันตรง ๆ (days[]) */ + return !info.days || info.days.indexOf(dayKey(dayDate(day))) !== -1; + } + return info.day === 'all' || info.day === day; /* เทียบกับวันที่กำลังดู ไม่ใช่ค่าของวันนี้ */ + } + /* 'weekday' / 'holiday' → วันที่สมมติขึ้นมา (ใช้ตรวจ days[] ให้ตรงกับวันที่ขอ) */ + function dayDate(day) { + var d = new Date(); + if (day === 'weekday') { var wd = (d.getDay() + 6) % 7; d.setDate(d.getDate() - wd); } + else if (day === 'holiday') { var wd2 = (d.getDay() + 6) % 7; d.setDate(d.getDate() + (5 - wd2)); } + return d; + } + function normDay(opts) { + if (opts && opts.dayType) return ALIAS[String(opts.dayType).toLowerCase()] || 'all'; + return todayType(); /* ค่าเริ่มต้น: ตรวจจากวันนี้ */ + } + + /* เวลาของจุดจอด ณ วันหนึ่ง ๆ = times พื้นฐาน + groups ที่ตรงกับวันนั้น */ + /* timesFor(stop, day) — day ที่ส่งมา (weekday/holiday) = "วันเป้าหมาย" ที่ต้องการดู + ทิศที่ผ่านการกรองวันมาแล้วจะส่ง day='all' → คืน times ตรง ๆ · ส่วนที่ยังไม่แยกวันใช้ groups แยกเอง */ + function timesFor(stop, day) { + var groups = (stop && stop.groups) || []; + if (!groups.length) return (stop && stop.times ? stop.times : []).slice(); + var out = ((stop && stop.times) || []).slice(); /* เวลาที่ไม่ผูกวัน = ใช้ทุกวัน */ + groups.forEach(function (g) { + var gt = g.dayType ? (ALIAS[String(g.dayType).toLowerCase()] || 'all') : 'all'; + if (gt !== 'all' && day && day !== 'all' && gt !== day) return; + out = out.concat(g.times || []); + }); + return out; + } + + /* ---------- โหลดข้อมูล: schedules.json เป็นได้ทั้ง "ไฟล์รวม" และ "สารบัญ" ---------- + - สารบัญ (index: true): routes[] มี { route_id, file } → โหลดเฉพาะไฟล์ของสายที่ขอ (lazy + cache) + - ไฟล์รวม (schema 2 เดิม): มี routes[] พร้อม directions ในตัว → ใช้ได้เหมือนเดิมไม่ต้องแก้โค้ดเก่า + - schema 1 เดิม: { schedules: [...] } → ใช้ได้เหมือนเดิม */ + var SUBS = {}; /* cache ไฟล์ย่อยต่อสาย */ + var subsReady = null; + function loadSubs() { + if (subsReady) return subsReady; + subsReady = fetch(DATA_URL + 'schedules.json', { cache: 'no-store' }) + .then(function (r) { return r.ok ? r.json() : null; }) + .then(function (d) { + if (!d || !d.index) return d; /* ไฟล์รวม → คืนทั้งไฟล์ */ + var rows = d.routes || []; + return Promise.all(rows.map(function (row) { + var file = row.file || ('schedules' + row.route_id + '.json'); + return fetch(DATA_URL + 'scheduleslist/' + file, { cache: 'no-store' }) + .then(function (x) { return x.ok ? x.json() : null; }) + .then(function (sub) { + if (!sub) return null; + var dirs = isSchema3(sub) ? directionsFromSchema3(sub) : (sub.directions || []); + SUBS[String(sub.route_id)] = { route_id: sub.route_id, station_order: sub.station_order || [], + directions: dirs, schema3: isSchema3(sub) }; + return SUBS[String(sub.route_id)]; + }).catch(function () { return null; }); + })).then(function (list) { + var routes = list.filter(Boolean); + return { schema: 2, index: true, routes: routes }; + }); + }) + .catch(function () { return null; }); + return subsReady; + } + /* โหลดสายเดียว (เร็ว — ใช้ตอนเปิดหน้า check/routes ของสายนั้น) */ + function loadRoute(rid) { + var key = String(rid); + if (SUBS[key]) return Promise.resolve({ schema: 2, routes: [SUBS[key]] }); + if (!subsReady) return loadSubs().then(function () { return SUBS[key] ? { schema: 2, routes: [SUBS[key]] } : null; }); + return Promise.resolve(SUBS[key] ? { schema: 2, routes: [SUBS[key]] } : null); + } + + /* ---------- ระยะทาง กม. (ไฟล์แยก resource/data/stop-km.json — สร้างโดย resource/tools/stop-km.py) ---------- + แยกไฟล์เพราะ schedules.json เป็นไฟล์ที่คนแก้มือ ถ้าเอาค่าคำนวณไปฝังไว้ พอบันทึกทับจากสำเนาเก่าจะหายทั้งชุด */ + var KM = {}; + var kmReady = null; + function loadKm() { + if (kmReady) return kmReady; + kmReady = fetch(DATA_URL + 'stop-km.json', { cache: 'no-store' }) + .then(function (r) { return r.ok ? r.json() : null; }) + .then(function (d) { + KM = (d && typeof d === 'object') ? d : {}; + try { window.dispatchEvent(new CustomEvent('schedules:km', { detail: { routes: Object.keys(KM).length } })); } catch (e) { } + return KM; + }) + .catch(function () { KM = {}; return KM; }); + return kmReady; + } + function absKm(rid, sid) { + var r = KM[String(rid)]; + if (!r) return null; + var v = r[String(sid)]; + return (typeof v === 'number') ? v : null; + } + /* km ของจุดในทิศนั้น — พลิกให้ "เพิ่มขึ้นตามทางที่รถวิ่ง" เพื่อให้ผลต่างมีเครื่องหมายถูกต้องเอง + (ลำดับจุดในทิศ + กม.จริงบนเส้น เป็นตัวบอกทิศ) */ + function relKms(rid, stops) { + var abs = (stops || []).map(function (s, i) { + var k = (s && typeof s.km === 'number') ? s.km : (s ? absKm(rid, s.station_id) : null); + return (typeof k === 'number') ? { i: i, k: k } : null; + }); + var known = abs.filter(Boolean); + if (known.length < 2) { + return (stops || []).map(function (s) { + if (s && typeof s.km === 'number') return s.km; + return s ? absKm(rid, s.station_id) : null; + }); + } + var forward = known[known.length - 1].k >= known[0].k; /* ทิศนี้วิ่งจาก กม. น้อย → มาก ใช่ไหม */ + var max = known.reduce(function (a, b) { return b.k > a ? b.k : a; }, known[0].k); + return abs.map(function (x) { if (!x) return null; return forward ? x.k : (max - x.k); }); + } + + /* โหลด holidays.json ครั้งเดียว (ถ้าไม่มีไฟล์ → ใช้กฎเสาร์–อาทิตย์) */ + var ready = null; + function loadHolidays() { + if (ready) return ready; + ready = fetch(DATA_URL + 'holidays.json', { cache: 'no-store' }) + .then(function (r) { return r.ok ? r.json() : null; }) + .then(function (d) { + HOLIDAYS = (d && Array.isArray(d.holidays)) ? d.holidays.slice() : []; + try { window.dispatchEvent(new CustomEvent('schedules:ready', { detail: { holidays: HOLIDAYS.length } })); } catch (e) { } + return HOLIDAYS; + }) + .catch(function () { HOLIDAYS = []; return HOLIDAYS; }); + return ready; + } + + /* ---------- ทิศทางของสาย (กรองตามวัน + ถอยกลับถ้าว่าง) ---------- */ + function directions(doc, routeId, opts) { + var rid = String(routeId); + var list = []; + if (hasSchema2(doc)) { + var r = (doc.routes || []).filter(function (x) { return String(x.route_id) === rid; })[0]; + if (!r) return []; + list = (r.directions || []).map(function (d) { + return { + dir_id: d.dir_id, + dir_label: d.dir_label, + days: Array.isArray(d.days) ? d.days.map(String) : null, /* ระบุวันตรง ๆ (อา จ อ พ พฤ ศ ส) */ + service: serviceOf(d, d), /* ตรวจวัน + เหตุผล (จากคำ/service/days) */ + autoTimes: !!d.autoTimes, /* true = คำนวณจุดที่ไม่มีตารางให้ */ + autoFor: Array.isArray(d.autoFor) ? d.autoFor.slice() : null, /* จำกัดเฉพาะจุดเหล่านี้ (ไม่ใส่ = ทุกจุดที่ว่าง) */ + travelMin: Number(d.travelMin) > 0 ? Number(d.travelMin) : null, /* เวลาเดินทางทั้งเส้น (นาที) */ + baseEnd: (d.baseEnd === 'first' || d.baseEnd === 'last') ? d.baseEnd : null, /* มีเวลาจริงที่ปลายไหน */ + baseSid: (d.baseSid != null ? d.baseSid : null), /* หรือระบุจุดอ้างอิงตรง ๆ */ + speedKmh: Number(d.speedKmh) > 0 ? Number(d.speedKmh) : DEFAULT_SPEED_KMH, + stops: (d.stops || []).map(function (s) { + return { + station_id: s.station_id, + times: s.times || [], + km: (typeof s.km === 'number') ? s.km : null, /* กม. จากต้นทาง (วัดโดย resource/tools/stop-km.py) */ + dir_note: s.dir_note || null, + note: s.note || null, + groups: s.groups || null, + derive: s.derive || null /* กฎ "จุดนี้ = เวลาจุดอ้างอิง ± n นาที" */ + }; + }) + }; + }); + } else { + /* schema 1 → ยังใช้ได้เหมือนเดิม (ไม่แยกวัน) */ + list = [{ dir_id: 'all', dir_label: null, service: 'all', stops: (doc && doc.schedules ? doc.schedules : []).filter(function (r) { + return String(r.route_id) === rid; + }).map(function (r) { + return { station_id: r.station_id, times: r.departure_times || [], dir_note: r.direction_note || null, note: r.schedule_note || null, groups: null }; + }) }]; + } + + var day = normDay(opts); + var kept = list.filter(function (d) { return applies(d.service, day); }); /* service = ผลตรวจวันของทิศนั้น */ + var fallback = false; + if (!kept.length && list.length) { kept = list.slice(); fallback = true; } /* ห้ามปล่อยว่าง */ + + warmStations(); /* เพื่อให้ข้อความ "คำนวณจาก ..." มีชื่อจุด */ + /* เวลาจริงรายจุดของ "ทั้งสาย" — กฎ derive อ้างจุดข้ามทิศได้ (เช่น 902: จุด 15 ← จุด 6 คนละทิศ) */ + var realByStation = {}; + (kept.length ? kept : list).forEach(function (d) { + (d.stops || []).forEach(function (s) { + var t0 = timesFor(s, day === 'all' ? 'all' : day); + if (t0.length && !realByStation[String(s.station_id)]) realByStation[String(s.station_id)] = t0; + }); + }); + + return kept.map(function (d) { + var kms = relKms(rid, d.stops); /* km ตามทางที่รถวิ่ง (จากไฟล์ stop-km.json) */ + /* ใส่ km ให้ "ทุกจุด" ก่อน — ต้องมีครบทั้งชุด ระบบหาจุดอ้างอิง/คำนวณความเร็วถึงจะทำงานได้ */ + var withKm = d.stops.map(function (s, si) { + var c = {}; + for (var k in s) c[k] = s[k]; + if (typeof c.km !== 'number' && typeof kms[si] === 'number') c.km = kms[si]; + return c; + }); + var speed = speedOf({ travelMin: d.travelMin, speedKmh: d.speedKmh, stops: withKm }); + var stops = withKm.map(function (s) { + var t = timesFor(s, day === 'all' ? 'all' : day); + var est = false; + var estFrom = null; /* ถ้าเป็นเวลาที่คำนวณ → ข้อมูลจุดอ้างอิง */ + /* ★ กฎของเจ้าของข้อมูล: "จุดนี้ = เวลาจุดอ้างอิง ± n นาที" (เขียนครั้งเดียวในไฟล์สาย) */ + if (s.derive && s.derive.from_station_id != null) { + var src = realByStation[String(s.derive.from_station_id)]; + if (src && src.length) { + t = shiftTimes(src, s.derive.offset_min); + est = true; + estFrom = { station_id: Number(s.derive.from_station_id), + name: stationNameOf(s.derive.from_station_id), + offsetMin: Number(s.derive.offset_min) || 0, + overrode: (timesFor(s, 'all').length > 0) }; + } + } + if (!est && d.autoTimes && !t.length) { /* ไม่มีตารางจริง → คำนวณจากจุดที่มีเวลา + กม. */ + var only = d.autoFor && d.autoFor.length + ? d.autoFor.map(String).indexOf(String(s.station_id)) !== -1 + : true; /* ไม่ระบุ autoFor = ทุกจุดที่ว่าง */ + if (only) { + var calc = computeTimes(s, withKm, { speedKmh: speed.kmh, baseEnd: d.baseEnd, baseSid: d.baseSid }); + if (calc && calc.length) { t = calc; est = true; } + } + } + return { station_id: s.station_id, times: t, km: s.km, dir_note: s.dir_note, note: s.note, + groups: s.groups, estimated: est, estimateFrom: estFrom, derive: s.derive || null }; + }); + return { dir_id: d.dir_id, dir_label: d.dir_label, service: d.service, days: d.days, autoTimes: d.autoTimes, + travelMin: d.travelMin, baseEnd: d.baseEnd, baseSid: d.baseSid, autoFor: d.autoFor, + speedKmh: Math.round(speed.kmh * 10) / 10, + speedFrom: speed.source, dayType: day, fallback: fallback, stops: stops }; + }); + } + + /* ---------- schema 2 → record แบน (คง API เดิม) ---------- */ + function records(doc, opts) { + if (!doc) return []; + if (!hasSchema2(doc)) return doc.schedules || (Array.isArray(doc) ? doc : []); + var out = []; + (doc.routes || []).forEach(function (r) { + directions(doc, r.route_id, opts).forEach(function (d) { + (d.stops || []).forEach(function (s) { + out.push({ + route_id: r.route_id, + station_id: s.station_id, + direction_note: s.dir_note || null, + dir_label: d.dir_label || null, /* ชื่อทิศ (ป่าโมกไปอยุธยา ฯลฯ) — ใช้เป็นหัวแถว */ + departure_times: s.times || [], + schedule_note: s.note || null, + estimated: !!s.estimated, /* true = เวลาคำนวณ ไม่ใช่ตารางจริง */ + estimateFrom: s.estimateFrom || null, /* { station_id, name, offsetMin } เมื่อคำนวณ */ + km: s.km, + dir_id: d.dir_id, + service: d.service, + days: d.days, + dayType: d.dayType, + fallback: d.fallback + }); + }); + }); + }); + return out; + } + + /* ---------- ข้อมูลของสายเดียว ---------- */ + function route(doc, routeId, opts) { + var rid = String(routeId); + var entries = records(doc, opts).filter(function (r) { return String(r.route_id) === rid; }); + var dirs = directions(doc, rid, opts); + var order = []; + if (hasSchema2(doc)) { + var r = (doc.routes || []).filter(function (x) { return String(x.route_id) === rid; })[0]; + if (r && r.station_order) order = r.station_order.slice(); + } + if (!order.length) { + entries.forEach(function (r) { if (order.indexOf(r.station_id) === -1) order.push(r.station_id); }); + order.sort(function (a, b) { return a - b; }); + } + return { route_id: rid, station_order: order, directions: dirs, entries: entries }; + } + + /* ---------- เวลาทั้งหมดของสาย (ไม่ซ้ำ + เรียง) ---------- */ + function times(doc, routeId, opts) { + var seen = {}; + records(doc, opts).forEach(function (r) { + if (String(r.route_id) !== String(routeId)) return; + (r.departure_times || []).forEach(function (t) { seen[t] = true; }); + }); + return Object.keys(seen).sort(); + } + + /* ---------- จำนวนเที่ยวของสาย ---------- */ + function countTrips(doc, routeId, opts) { + var n = 0; + records(doc, opts).forEach(function (r) { + if (String(r.route_id) === String(routeId)) n += (r.departure_times || []).length; + }); + return n; + } + + loadHolidays(); /* เริ่มโหลดทันที (ไม่บล็อกการอ่าน) */ + loadKm(); + + window.Schedules = { + hasSchema2: hasSchema2, + load: loadSubs, /* โหลดทุกสาย (จากสารบัญหรือไฟล์รวม) */ + loadRoute: loadRoute, /* โหลดสายเดียว + ไฟล์ย่อยที่ยังไม่เคยโหลด */ + normSub: normSub, + get subs() { return SUBS; }, + records: records, + route: route, + directions: directions, + times: times, + countTrips: countTrips, + /* ส่วนของวันทำงาน/วันหยุด */ + todayType: todayType, + dayTypeOf: dayTypeOf, + dayInfo: dayInfo, + dayKey: dayKey, + DAYS: DAYS, + DAY_TH: DAY_TH, + DAY_ABBR: DAY_ABBR, + detectDay: detectDay, + detectDayOfDir: detectDayOfDir, + offsetLabel: offsetLabel, + stationNameOf: stationNameOf, + setStationNames: setStationNames, + shiftTimes: shiftTimes, + serviceOf: serviceOf, + timesFor: timesFor, + computeTimes: computeTimes, + speedOf: speedOf, + absKm: absKm, + relKms: relKms, + loadKm: loadKm, + get km() { return KM; }, + DEFAULT_SPEED_KMH: DEFAULT_SPEED_KMH, + loadHolidays: loadHolidays, + get holidays() { return HOLIDAYS.slice(); }, + ready: ready + }; +})(); diff --git a/ui/partials/stopDetail.html b/ui/partials/stopDetail.html index fd162cc..2f15ded 100644 --- a/ui/partials/stopDetail.html +++ b/ui/partials/stopDetail.html @@ -1,4 +1,18 @@