Files
web-at-transit-mock/resource/tools/qgis-to-web.py
T
Bkk1234 488b4c6054 แผนที่ blog 4-5 จาก shapefile + แปล EN บทความ 3-4 + ป้าย tag บนแผนที่
== แผนที่บทความ (blog) ==
- blog/3: map ใหม่ 5 เส้นตามเนื้อหา (902 · 15 · 952 · 101 · 324) — เดิมเป็นสำเนาของ blog/2
- blog/4: map 2 แนวทางจาก QGIS Project/รถมินิบัส แสวงหา-กรุงเทพ
    · แนวทาง 1  แสวงหา-โพธิ์ทอง-กรุงเทพ (127.2 กม.)
    · แนวทาง 2  แยก 1011 เป็น 2 ช่วง: อ่างทอง-โพธิ์ทอง-แสวงหา + แสวงหา-สีบัวทอง
- blog/5: map 3 เส้นจาก QGIS Project/amphoeroutes (ข้อเสนอขั้นต่ำ)
    · สามโก้-วิเศษ-อ่างทอง · แสวงหา-โพธิ์ทอง-อ่างทอง · ไชโย-อ่างทอง-ป่าโมก
- ป้าย tag แสดงบนแผนที่ด้วย (.blog-mapx-tag มุมขวาบน — หลบปุ่มซูมของ Leaflet)

== เครื่องมือ qgis-to-web.py ==
- SHP_MAP +6 (รวมโฟลเดอร์ย่อย: รถมินิบัส แสวงหา-กรุงเทพ/ · amphoeroutes/)
- แก้บั๊ก: โหมด shp เคยตัด "-" ออกจากชื่อ dream-* ทำให้หา SHP_MAP ไม่เจอ

== ข้อความ (blog-data) ==
- text3: แปล EN ใหม่ให้ตรงกับ TH (เดิมเป็นสำเนาของ text2 — ชื่อการ์ดซ้ำกันใน #/blog)
- text4-6: ตรวจ/แปล EN ครบ · TH = EN ทุกไฟล์
- pic5.jpg · pic6.jpg (รูปประกอบบทความ 5-6)

== geojson ใหม่ 6 เส้น (dream-*) ==
sawangha-bangkok · angthong-phothong-sawangha · sawangha-srinuathong
samko-wisad-angthong · sawangha-phothong-angthong · chaiyo-angthong-pamok
2026-10-06 02:43:21 +07:00

376 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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 (เส้นทางเดิม)
python resource/tools/qgis-to-web.py --from gpkg # อ่าน angthongtoanytrain/*.gpkg (เส้นทางที่เสนอ/ความฝัน)
ธงอื่น:
--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"
SRC_GPKG = QDIR / "angthongtoanytrain" # เส้นทางที่เสนอ (ยังไม่มีจริง) — 1 ไฟล์ = 1 เส้นทาง
DST = ROOT / "resource" / "data" / "geojson-web"
# ── ตารางจับคู่ "ชื่อไฟล์ .gpkg → route_id" (เส้นทางที่เสนอ) ──────────────────
# route_id ต้องไม่ชนกับสายจริง (902/15/951/952/954/8/101/464/641/2194/324/1011/2231/999)
# ชื่อไฟล์ .gpkg เป็นภาษาไทยได้ — คีย์คือชื่อ stem (ไม่รวม .gpkg)
GPKG_MAP = {
"อ่างทอง-บ้านภาชี(สายสีแดงเข้ม)": "dream-banchang",
"อ่างทอง-รถไฟฟ้าชานเมืองอยุธยา(สายสีแดงเข้ม)": "dream-ayutthaya-redline",
"อ่างทอง-สถานีรถไฟความเร็วสูงอยุธยา": "dream-ayutthaya-hsr",
"อ่างทอง-เมืองทองธานี": "dream-muangthong",
"อ่างทอง-แยกปากเกร็ด": "dream-pakkret",
"อ่างทอง-วัชรพล": "dream-Watcharapol",
}
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",
# เส้นทางที่เสนอเพิ่มเติม (อยู่ในโฟลเดอร์ย่อยของ QGIS Project — stem มี path ได้)
"dream-sawangha-bangkok": "รถมินิบัส แสวงหา-กรุงเทพ/Sawangha-bangkok",
"dream-angthong-phothong-sawangha": "รถมินิบัส แสวงหา-กรุงเทพ/angthong-phothong-sawangha",
"dream-sawangha-srinuathong": "รถมินิบัส แสวงหา-กรุงเทพ/sawangha-srinuathong",
# amphoeroutes/ — รถเชื่อมต่ออำเภอเข้าเมือง (ตามบทความ 5)
"dream-samko-wisad-angthong": "amphoeroutes/samko-wisad-angthong",
"dream-sawangha-phothong-angthong": "amphoeroutes/sawangha-phothong-angthong",
"dream-chaiyo-angthong-pamok": "amphoeroutes/chaiyo-angthong-pamok",
"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
# ── อ่าน GeoPackage (.gpkg = SQLite) — ไม่ต้องพึ่ง GDAL/geopandas ──
def read_gpkg(path):
"""คืน (lines, srs_id, ชื่อชั้น) — รองรับ LineString/MultiLineString · พิกัด (lng, lat)
GPKG geometry blob = 'GP' + ver(1) + flags(1) + srs_id(4) + envelope(ตาม flags) + WKB"""
import sqlite3
con = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
try:
cur = con.cursor()
row = cur.execute(
"SELECT table_name FROM gpkg_contents WHERE data_type='features' LIMIT 1").fetchone()
if not row:
return None, None, None
table = row[0]
srs = cur.execute("SELECT srs_id FROM gpkg_geometry_columns WHERE table_name=?",
(table,)).fetchone()
blob = cur.execute(f'SELECT geometry FROM "{table}" LIMIT 1').fetchone()[0]
finally:
con.close()
return _parse_gpkg_blob(blob), (srs[0] if srs else None), table
def _parse_gpkg_blob(blob):
"""ถอด WKB จาก GPKG blob → list ของเส้น; แต่ละเส้น = list ของ [lng, lat]"""
if not blob or blob[:2] != b"GP":
return []
flags = blob[3]
env = {0: 0, 1: 4, 2: 6, 3: 6, 4: 8}.get((flags >> 1) & 0x07, 0)
o = 8 + env * 8
order = blob[o]
E = "<" if order == 1 else ">"
gtype = struct.unpack(E + "I", blob[o + 1:o + 5])[0]
o += 5
lines = []
if gtype == 2: # LineString
n = struct.unpack(E + "I", blob[o:o + 4])[0]
o += 4
lines.append([list(struct.unpack(E + "dd", blob[o + 16 * i:o + 16 * i + 16]))
for i in range(n)])
elif gtype == 5: # MultiLineString
n = struct.unpack(E + "I", blob[o:o + 4])[0]
o += 4
for _ in range(n):
E2 = "<" if blob[o] == 1 else ">"
m = struct.unpack(E2 + "I", blob[o + 5:o + 9])[0]
o += 9
lines.append([list(struct.unpack(E2 + "dd", blob[o + 16 * i:o + 16 * i + 16]))
for i in range(m)])
o += 16 * m
return [l for l in lines if len(l) >= 2]
def from_gpkg(route_id):
"""คืน (features, รายงาน) จาก angthongtoanytrain/<ชื่อ>.gpkg ตาม GPKG_MAP"""
stem = next((k for k, v in GPKG_MAP.items() if v == route_id), None)
if stem is None:
return None, ["ไม่มีในตาราง GPKG_MAP — ข้าม"]
path = SRC_GPKG / f"{stem}.gpkg"
if not path.exists():
return None, [f"ไม่พบไฟล์ {path.name} (ชื่อเปลี่ยน? แก้ GPKG_MAP)"]
lines, srs, table = read_gpkg(path)
if not lines:
return None, ["ไม่มีเส้นในไฟล์ (หรือชนิด geometry ไม่รองรับ)"]
if srs not in (None, 4326):
return None, [f"SRS = {srs} (ไม่ใช่ EPSG:4326) — บันทึกใหม่ใน QGIS"]
if looks_like_utm(lines):
return None, ["พิกัดเป็น UTM (ไม่ใช่ WGS84) — บันทึกใหม่โดยตั้ง CRS = EPSG:4326"]
kept, dropped = clean_lines(lines)
if not kept:
return None, ["หลังกรองแล้วไม่มีเส้นเหลือ — ข้าม"]
geom = ("MultiLineString" if len(kept) > 1 else "LineString")
feat = {"type": "Feature", "properties": {"route_id": route_id},
"geometry": {"type": geom, "coordinates": (kept if len(kept) > 1 else kept[0])}}
notes = [f"ชั้น '{table}' · srs={srs}"]
if dropped:
notes.append(f"ตัด {dropped} ช่วงที่สั้น/หลุดกรอบ")
return [feat], notes
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)
if mode == "gpkg":
return sorted(GPKG_MAP.values())
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", "gpkg"], 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 = {"shp": "shapefile (QGIS Project/*.shp)",
"geojson": "GeoJSON-2/*.geojson",
"gpkg": "angthongtoanytrain/*.gpkg (เส้นทางที่เสนอ)"}[args.src]
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:
keyed = args.src == "shp" and rid in SHP_MAP # ชื่อตรงตารางแล้ว (dream-* มี "-") — ห้ามตัด
if not keyed and args.src != "gpkg":
rid = re.sub(r"[^0-9A-Za-z]", "", rid) or rid
if args.src == "shp":
feats, notes = from_shp(rid)
elif args.src == "gpkg":
feats, notes = from_gpkg(rid)
else:
feats, notes = 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()