#!/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()