ตารางเวลาคำนวณได้ + หน้ารายละเอียดป้ายขับเคลื่อนด้วยข้อมูล + แผนที่ Leaflet

Schedules — กติกา "จุดนี้ = เวลาจุดอ้างอิง ± n นาที"
- ฟิลด์ derive { from_station_id, offset_min } คำนวณที่ ui/partials/schedules.js (ท่อเดียว) รองรับอ้างจุดข้ามทิศ
- จุดย่อยของ "8 other_stop" ใช้ offsets_min จับคู่ตามลำดับ (เช่น ตลาดสามโก้ = ตลาดท่าช้าง +45 นาที)
- เครื่องมือ resource/tools/derive-times.py + ตาราง resource/data/derive-times.csv (--check / --audit ชี้จุดที่ควรตั้งกฎ)
- แยกตารางเป็นรายสาย: scheduleslist/schedules<route_id>.json และ schedules.json เป็นสารบัญ (โหลดแบบ lazy + cache)
- ตรวจจับวันทำงาน/วันหยุด + schema 3 (weekday/holiday → directions) · ไฟล์ข้อมูลเป็น CRLF ทั้งชุด
- ล้างค่าที่ไม่ใช่ HH:MM ที่ฝังใน times (ทำให้ KPI เพี้ยน) + กันค่าหลอกในตัวสรุปเวลา

UI
- หน้ารายละเอียดป้าย/ตารางเวลา ขับเคลื่อนด้วย JSON (stopDetail.init.js) · จุดขึ้นรถประจำทางอื่นๆ รองรับหลายจุดต่อสาย
- #/stops: แสดง 6 ป้ายแรก + ปุ่ม "แสดงป้ายทั้งหมด" (โหลดรูปเฉพาะที่แสดง) · ชิปสาย → #/routes/<route_id>
- หน้าแรก: ตัดตัวเลือก "ทุกสถานีในจังหวัดนี้" · ตัวกรองจังหวัด/สถานี + ปุ่มแชร์ (share URL)
- การ์ดติดต่อ: ไอคอน/ชื่อ/สีเปลี่ยนตามชนิด URL (Facebook / LINE / เว็บไซต์) + ปุ่มเปิดลิงก์จาก web_url
- รูปรองรับหลายนามสกุล (.jpg → .jpeg → .webp → .png) · ป้าย "ประมาณ" + หมายเหตุสำหรับตารางที่คำนวณ
- หน้าเครดิตเหลือ 3 หมวด · แก้ข้อความหมวดแผนที่ให้ตรงกับข้อมูลจริง
- แผนที่ Leaflet (vendor ในโปรเจกต์ ไม่ใช้ CDN): เส้นทาง + หมุด + ป๊อปอัป · แก้ CSS ที่ทำให้ SVG ยุบ 0x0

เครื่องมือและเอกสาร
- qgis-to-web.py อ่าน .shp ตรง → geojson-web (สร้างใหม่ 10 ไฟล์) + audit-geojson.py ตรวจ 3 ส่วน
- stop-km.py วัดระยะ กม. ตามเส้นจริง → stop-km.json · schedules-editor.html (แก้ทีละไฟล์ · มุมมองตารางแบบ Excel)
- AGENTS.md: กติกา derive · offsets_min · นามสกุลรูป · ชิปสาย · หน้ารายละเอียดป้ายมาจากไหน
This commit is contained in:
Bkk1234 committed 2026-09-30 03:25:18 +07:00
1 parent 88311326e6
commit 1cfaeb1526
91 files changed
+7560 -844

No files matched your search

+263
View File
@@ -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("<i", rec[:4])[0] != 3:
continue # ข้ามชนิดที่ไม่ใช่เส้น
nparts, npoints = struct.unpack("<ii", rec[36:44])
parts = struct.unpack("<%di" % nparts, rec[44:44 + 4 * nparts])
poff = 44 + 4 * nparts
pts = [struct.unpack("<dd", rec[poff + 16 * i:poff + 16 * i + 16]) for i in range(npoints)]
lines = []
for i in range(nparts):
a = parts[i]
z = parts[i + 1] if i + 1 < nparts else npoints
if pts[a:z]:
lines.append([[x, y] for x, y in pts[a:z]])
if lines:
recs.append(lines)
return recs
def prj_ok(path):
"""ตรวจ .prj ว่าเป็น WGS84 (ไม่ใช่ UTM/meters) — ไม่มี .prj = เตือนแต่ไปต่อ (มีตัวกรอง bbox อีกชั้น)"""
prj = path.with_suffix(".prj")
if not prj.exists():
return None # ไม่มีข้อมูล CRS
t = prj.read_text(encoding="utf-8", errors="replace")
if "UTM" in t or "Transverse_Mercator" in t:
return False
return "4326" in t or "WGS_1984" in t
# ── ตัวกรอง/ทำความสะอาด (ใช้ร่วมกันทั้งสองแหล่ง) ──
def clean_lines(lines):
lng0, lng1, lat0, lat1 = BBOX
kept, dropped = [], 0
for l in lines:
good = [c for c in l if lng0 < float(c[0]) < lng1 and lat0 < float(c[1]) < lat1]
if len(good) >= 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()