Files
Bkk1234 750b4a2ea8 mock: three search tabs - stop code, place name, near me
- busStop.html: added the third tab (data-mode=near) and its own panel with
  the location button, hint and result area; removed the near button from the
  toolbar and deleted the old on-screen numpad markup
- busStop.search.js: MODE_NEAR in setMode, disables the other panels, hides
  the stop list while ranked results are shown, skips filtering in that mode,
  and removed the dead initNumpad code
- security gate: the tab is revealed only when isSecureContext and
  navigator.geolocation exist; otherwise it stays hidden and the mode is
  refused
- map.js: re-enable the button after a successful lookup
- i18n: stops.modeNear / nearCta / nearHint
- bump SW version to 2026.09.27.98

Verified on localhost:8090 - three tabs, near mode shows a map with 8 ranked
stops, button re-enables and works again, switching back restores the list;
with isSecureContext forced false the tab is hidden and unselectable.
2026-10-24 00:11:56 +07:00

767 lines
39 KiB
JavaScript
Raw Permalink 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.
/* ============================================================
Atroute — แผนที่เส้นทาง (Leaflet, vanilla)
------------------------------------------------------------
ข้อมูล:
<base>geojson-web/<route_id>.geojson เส้นทางจริงจาก QGIS (WGS84)
<base>busstop_list.json 154 ป้าย (มีพิกัด + buses-line)
<base>stations.json 19 สถานีของเรา (13 มีพิกัด)
<base>routes.json สาย ↔ สถานี
ธีม DESIGN.md §5: เส้นทาง --green-700 หนา 5px · หมุดสี่เหลี่ยมมน
ออฟไลน์: ยังวาดเส้นทาง/หมุดจากข้อมูลในเครื่องได้โดยไม่ต้องมี tile
API:
ATMap.route(el, '101') #/routes/:id
ATMap.forStop(el, 'at_main_terminal') #/stops/:code
ATMap.nearMe(button, resultEl) #/stops (ป้ายใกล้ฉัน)
ทุกตัวรับ opts = { base, stopHref } (สำหรับหน้า static นอก SPA)
============================================================ */
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 = '&copy; OpenStreetMap';
var NEAR_M = 40; /* ป้ายอยู่ "บนเส้นทาง" ถ้าใกล้ ≤ 40 ม. */
var STATION_NEAR_M = 80; /* สถานีอยู่ "ตามเส้นทาง" ถ้าใกล้ ≤ 80 ม. */
var LINE_W = 5;
var LINE_MAIN = '#14532d'; /* --green-700 */
var SHADES = ['#14532d', '#1f7a3d', '#2f8f5b', '#4a7c59', '#166534'];
var TH = { minLng: 97, maxLng: 103, minLat: 12, maxLat: 17.5 };
var cache = {};
/* ---------- พื้นฐาน ---------- */
function t(k, vars) { return window.I18N ? I18N.t(k, vars) : k; }
function esc(s) {
return String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;')
.replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
function num(v) {
var n = typeof v === 'number' ? v : parseFloat(v);
return isFinite(n) ? n : null;
}
function pointOf(o) {
var lat = num(o && o.latitude), lng = num(o && o.longitude);
return (lat === null || lng === null) ? null : [lng, lat];
}
function url(o, path) { return ((o && o.base) || DEF_BASE) + path; }
function href(o, code) {
return (o && o.stopHref) ? o.stopHref(code) : '#/stops/' + encodeURIComponent(code);
}
function fetchJSON(u) {
return fetch(u, { cache: 'no-store' }).then(function (r) { return r.ok ? r.json() : null; }).catch(function () { return null; });
}
/* ---------- เรขาคณิต ---------- */
function hav(a, b) {
var R = 6371000, p1 = a[1] * Math.PI / 180, p2 = b[1] * Math.PI / 180;
var dp = p2 - p1, dl = (b[0] - a[0]) * Math.PI / 180;
var x = Math.sin(dp / 2) * Math.sin(dp / 2) + Math.cos(p1) * Math.cos(p2) * Math.sin(dl / 2) * Math.sin(dl / 2);
return 2 * R * Math.asin(Math.sqrt(x));
}
function segDist(p, a, b) {
var lat0 = (a[1] + b[1]) / 2 * Math.PI / 180, k = 111320;
var ax = a[0] * Math.cos(lat0) * k, ay = a[1] * k;
var bx = b[0] * Math.cos(lat0) * k, by = b[1] * k;
var px = p[0] * Math.cos(lat0) * k, py = p[1] * k;
var dx = bx - ax, dy = by - ay, L2 = dx * dx + dy * dy;
if (!L2) return { d: Math.hypot(px - ax, py - ay), t: 0 };
var u = Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / L2));
return { d: Math.hypot(px - (ax + u * dx), py - (ay + u * dy)), t: u };
}
function linesOf(geom) {
if (!geom) return [];
var out = geom.type === 'LineString' ? [geom.coordinates] : (geom.coordinates || []);
return out.map(function (l) {
return l.filter(function (c) { return c[0] > TH.minLng && c[0] < TH.maxLng && c[1] > TH.minLat && c[1] < TH.maxLat; });
}).filter(function (l) { return l.length >= 2; });
}
function flatten(geo) {
return geo ? geo.features.reduce(function (a, f) { return a.concat(linesOf(f.geometry)); }, []) : [];
}
function lineLengthKm(lines) {
var m = 0;
lines.forEach(function (l) { for (var i = 1; i < l.length; i++) m += hav(l[i - 1], l[i]); });
return m / 1000;
}
function toLatLngs(lines) {
return lines.map(function (l) { return l.map(function (c) { return [c[1], c[0]]; }); });
}
/* ระยะสะสม (กม.) จากต้นทางถึงจุดที่ใกล้จุด p ที่สุด บนเส้นที่ยาวที่สุด */
function kmFromStart(mainLine, p) {
var best = { d: Infinity, km: 0 }, cum = 0;
for (var i = 1; i < mainLine.length; i++) {
var a = mainLine[i - 1], b = mainLine[i], seg = hav(a, b), r = segDist(p, a, b);
if (r.d < best.d) best = { d: r.d, km: (cum + r.t * seg) / 1000 };
cum += seg;
}
return best;
}
function longest(lines) {
return lines.slice().sort(function (a, b) {
var la = 0, lb = 0;
for (var i = 1; i < a.length; i++) la += hav(a[i - 1], a[i]);
for (var j = 1; j < b.length; j++) lb += hav(b[j - 1], b[j]);
return lb - la;
})[0];
}
/* ---------- โหลดข้อมูล (cache) ---------- */
function loadGeo(id, o) {
var key = 'geo:' + id;
if (cache[key] === undefined) cache[key] = fetchJSON(url(o, 'geojson-web/' + id + '.geojson'));
return Promise.resolve(cache[key]);
}
function loadJson(file, key, o) {
if (cache[key] === undefined) cache[key] = fetchJSON(url(o, file));
return Promise.resolve(cache[key]);
}
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, si) {
stops.push({
name: sub.name,
pt: sub.hasCoord ? [sub.lng, sub.lat] : null,
code: null,
note: o.note || null,
subStop: true, /* ★ จุดย่อย: ลิงก์ไปหน้ารวมจุดขึ้นรถของสายนี้ */
subRoute: String(route.route_id),
subFirst: si === 0 /* จุดแรก = จุดอ้างอิง (อยู่บน timetable แล้ว) */
});
});
});
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);
if (s.subStop) s.sub = true; /* คงธงจุดย่อยไว้ให้ตัววาดหมุด */
});
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, 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: '<span class="at-pin ' + kind + '"></span>', iconSize: [16, 16], iconAnchor: [8, 8] });
}
function legend(el, rows) {
var box = document.createElement('div');
box.className = 'at-legend';
rows.forEach(function (r) {
var d = document.createElement('div'), sw = document.createElement('i');
if (r.square) sw.className = 'sq';
sw.style.background = r.color;
d.appendChild(sw);
d.appendChild(document.createTextNode(r.label));
box.appendChild(d);
});
el.appendChild(box);
}
function caption(el, html) {
var c = el.parentNode && el.parentNode.querySelector('.at-map-caption');
if (c) c.innerHTML = html;
}
function fitAll(map, latlngs) {
var all = [];
latlngs.forEach(function (l) {
/* รับได้ทั้ง "เส้น" ([ [lat,lng], ... ]) และ "จุดเดี่ยว" ([lat, lng]) */
if (l && typeof l[0] === 'number' && typeof l[1] === 'number') all.push([l[0], l[1]]);
else if (l && l.length) all = all.concat(l);
});
if (!all.length) return;
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) {
var s = h.stop, pt = pointOf(s);
if (!pt) return;
var short = [];
if (s.kilometer) short.push(t('map.km') + ' ' + s.kilometer);
if (s.position) short.push(s.position);
if (s.type) short.push(s.type);
var html = '<div class="at-pop">';
html += '<b>' + esc(s.place || s.type || t('map.legendStop')) + '</b>';
var meta = [];
if (s.kilometer) meta.push(t('map.km') + ' ' + s.kilometer);
if (s.position) meta.push(s.position);
if (s.type && s.place) meta.push(s.type); /* ซ้ำกับหัวข้อเมื่อไม่มีชื่อสถานที่ */
if (meta.length) html += '<span>' + esc(meta.join(' · ')) + '</span>';
var bl = s['buses-line'] || [];
if (bl.length) html += '<span>' + esc(t('map.servedBy')) + ': <b>' + esc(bl.join(', ')) + '</b></span>';
html += '<a href="' + mapsLink(s.latitude, s.longitude) + '" target="_blank" rel="noopener">' + esc(t('map.openInMaps')) + '</a>';
html += '</div>';
L.marker([pt[1], pt[0]], { icon: pinIcon('stop') })
.bindTooltip(esc(short.join(' · ')), { direction: 'top', offset: [0, -8] })
.bindPopup(html, { closeButton: false, offset: [0, -6] })
.addTo(group);
});
}
/* จุดย่อยของ "จุดขึ้นรถประจำทางอื่นๆ" (จาก 8 other_stop.json) — ปักหมุดสี่เหลี่ยมม่วง
คลิก = popup ชื่อ + กม. + ลิงก์ไปหน้ารวมจุดขึ้นรถของสายนั้น */
function drawSubStops(map, rows, routeId, group) {
(rows || []).forEach(function (r) {
if (!r.sub || !r.pt) return;
var html = '<div class="at-pop"><b>' + esc(r.name) + '</b>';
html += '<span>' + esc(t('map.subStop')) + (r.km != null && r.km !== '' ? ' · ' + esc(r.km) + ' ' + esc(t('map.km')) : '') + '</span>';
if (r.href) html += '<a href="' + esc(r.href) + '">' + esc(t('map.viewBoardingPoints')) + '</a>';
html += '</div>';
L.marker([r.pt[1], r.pt[0]], { icon: pinIcon('sub'), zIndexOffset: 400 })
.bindTooltip(esc(r.name), { direction: 'top', offset: [0, -8] })
.bindPopup(html, { closeButton: false, offset: [0, -6] })
.addTo(group);
});
}
/* สถานีของเรา: ชื่อ + คลิกไปหน้ารายละเอียดป้าย (opts.stopHref) */
function drawStations(map, hits, opts, group) {
hits.forEach(function (h) {
var s = h.station, pt = pointOf(s);
if (!pt) return;
var html = '<div class="at-pop"><b>' + esc(s.station_name_th) + '</b>';
html += '<span>' + esc([s.city_th, s.province_th].filter(Boolean).join(' · ')) + '</span>';
if (s.station_code) html += '<a href="' + esc(href(opts, s.station_code)) + '">' + esc(t('map.viewStopPage')) + '</a>';
html += '</div>';
L.marker([pt[1], pt[0]], { icon: pinIcon('term') })
.bindTooltip('<b>' + esc(s.station_name_th) + '</b><br>' + esc(s.province_th || ''), { direction: 'top', offset: [0, -9] })
.bindPopup(html, { closeButton: false, offset: [0, -6] })
.addTo(group);
});
}
/* สถานีที่จะปักหมุด (ไอคอนเหลือง)
- allowedIds = routes.json → station_ids ของสายนั้น (ปักเฉพาะที่ระบุไว้ — ให้ตรงกับตาราง)
- ไม่ส่ง allowedIds = พฤติกรรมเดิม (ปักทุกสถานีที่อยู่ใกล้เส้น) */
function stationsNear(lines, maxM, o, allowedIds) {
return stationList(o).then(function (list) {
var hits = [];
var allow = (allowedIds && allowedIds.length) ? allowedIds.map(String) : null;
list.forEach(function (s) {
if (allow && allow.indexOf(String(s.station_id)) === -1) return; /* ไม่อยู่ในสายนี้ → ไม่ปัก */
var pt = pointOf(s);
if (!pt) return;
var best = Infinity;
for (var i = 0; i < lines.length && best > maxM; i++) {
var l = lines[i];
for (var j = 1; j < l.length; j++) {
var r = segDist(pt, l[j - 1], l[j]);
if (r.d < best) best = r.d;
}
}
if (best <= maxM) hits.push({ station: s, dist: best });
});
return hits;
});
}
function stopsNear(lines, o) {
return stops(o).then(function (list) {
var hits = [];
list.forEach(function (s) {
var pt = pointOf(s);
if (!pt) return;
var best = Infinity;
for (var i = 0; i < lines.length && best > NEAR_M; i++) {
var l = lines[i];
for (var j = 1; j < l.length; j++) {
var r = segDist(pt, l[j - 1], l[j]);
if (r.d < best) best = r.d;
}
}
if (best <= NEAR_M) hits.push({ stop: s, dist: Math.round(best) });
});
return hits;
});
}
/* รายการสถานีตามเส้นทาง พร้อม กม. จากต้นทาง */
function renderKmList(el, list) {
var host = document.getElementById(el);
if (!host) return;
host.innerHTML = '';
if (!list.length) return;
list.forEach(function (x) {
var li = document.createElement('li');
var row = document.createElement(x.href ? 'a' : 'div');
if (x.href) row.href = x.href;
row.className = 'at-km-row' + (x.href ? '' : ' is-plain') + (x.sub ? ' is-sub' : '');
if (x.note) row.title = x.note;
var val = x.off ? '<span class="is-off">' + esc(t('map.offRoute')) + '</span>'
: (x.km === null || x.km === '' ? '–' : x.km + ' ' + esc(t('map.km')));
row.innerHTML = '<span class="at-km-dot" aria-hidden="true"></span>' +
'<span class="at-km-name">' + esc(x.name) + '</span>' +
'<span class="at-km-val">' + val + '</span>';
li.appendChild(row);
host.appendChild(li);
});
var wrap = host.closest('.at-km-wrap');
if (wrap) wrap.hidden = false;
}
/* ============================================================
#/routes/:id — เส้นทาง + สถานีตามเส้นทาง (พร้อม กม.) + ป้าย
============================================================ */
function route(el, routeId, opts) {
if (!el || !window.L) return;
opts = opts || {};
loadGeo(routeId, opts).then(function (geo) {
var lines = flatten(geo);
if (!lines.length) {
el.classList.add('is-offline');
caption(el, '<span class="at-offline">' + esc(t('map.empty')) + '</span>');
return;
}
var m = makeMap(el), map = m.map, group = L.layerGroup().addTo(map);
var latlngs = toLatLngs(lines);
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) {
L.marker(e[0], { icon: pinIcon('term') })
.bindTooltip(esc(e[1]), { direction: 'top', offset: [0, -8] }).addTo(group);
});
Promise.all([stopsNear(lines, opts), routeList(opts),
stationList(opts), otherStopList(opts)]).then(function (res) {
var shelters = res[0], routesDoc = res[1], stations = res[2], others = res[3];
var routeDoc = (routesDoc || []).filter(function (r) { return String(r.route_id) === String(routeId); })[0];
var allowed = routeDoc ? (routeDoc.station_ids || []) : null; /* ★ ปักเฉพาะสถานีที่สายระบุ */
drawShelters(map, shelters, group);
stationsNear(lines, STATION_NEAR_M, opts, allowed).then(function (sts) {
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 route = routeDoc;
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) {
/* จุดย่อย → ลิงก์ไป #/stops/other_stop?route=<รหัสสาย> (หน้ารวมจุดขึ้นรถของสายนั้น) */
var linkHref = x.code ? href(opts, x.code)
: (x.subStop ? '#/stops/other_stop?route=' + encodeURIComponent(x.subRoute) : null);
return { name: x.name, km: x.km, off: x.off, note: x.note, href: linkHref, sub: !!x.subStop };
}).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);
drawSubStops(map, routeStopRows(route, stations, others, main,
(routesDoc || []).map(function (r) { return String(r.route_id); })), route.route_id, group);
var parts = ['<b>' + esc(routeId) + '</b> · ' + esc(t('map.captionRoute', { km: lineLengthKm(lines).toFixed(1), n: shelters.length }))];
if (rows.length) parts.push(esc(t('map.stations')) + ' <b>' + rows.length + '</b>');
if (m.offline) parts.push('<span class="at-offline">' + esc(t('map.offline')) + '</span>');
caption(el, parts.join(' · '));
});
legend(el, [
{ color: LINE_MAIN, label: t('map.legendRoute') },
{ color: '#1f7a3d', square: true, label: t('map.legendStop') },
{ color: '#f2a900', square: true, label: t('map.legendTerminal') },
{ color: '#7a4cc0', square: true, label: t('map.legendSubStop') }
]);
});
}
/* ============================================================
#/stops/:code — เส้นทางที่ผ่านป้ายนี้ + หมุดตัวป้าย
============================================================ */
function forStop(el, code, opts) {
if (!el || !window.L) return;
opts = opts || {};
Promise.all([stationList(opts), loadJson('routes.json', 'routes', opts)]).then(function (res) {
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) {
el.classList.add('is-offline');
caption(el, '<span class="at-offline">' + esc(t(st ? 'map.noRoutesHere' : 'map.empty')) + '</span>');
return;
}
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, specs = [];
geos.forEach(function (g, idx) {
var lines = flatten(g);
if (!lines.length) return;
var color = SHADES[drawn % SHADES.length];
drawn++;
allLines = allLines.concat(lines);
toLatLngs(lines).forEach(function (l) {
specs.push({ latlngs: l, color: color });
all.push(l);
});
legendRows.push({ color: color, label: t('map.route') + ' ' + ids[idx] });
});
if (!all.length) {
el.classList.add('is-offline');
caption(el, '<span class="at-offline">' + esc(t('map.empty')) + '</span>');
return;
}
drawLines(group, specs);
stopsNear(allLines, opts).then(function (shelters) {
drawShelters(map, shelters, group);
/* 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('<b>' + esc(pinName) + '</b><br>' + esc(t('map.thisStop')), { direction: 'top', offset: [0, -11] })
.addTo(group);
all.push([[stPt[1], stPt[0]]]);
}
fitAll(map, all);
var parts = [esc(t('map.captionStop', { r: drawn, n: shelters.length }))];
parts.push(stPt ? esc(t('map.stationPinned')) : esc(t('map.noStationPin')));
if (m.offline) parts.push('<span class="at-offline">' + esc(t('map.offline')) + '</span>');
caption(el, parts.join(' · '));
});
legendRows.push({ color: '#1f7a3d', square: true, label: t('map.legendStop') });
legendRows.push({ color: '#f2a900', square: true, label: t('map.legendHere') });
legend(el, legendRows);
});
});
}
/* ============================================================
ป้ายใกล้ฉัน — geolocation → ป้ายที่ใกล้ที่สุด + แผนที่
============================================================ */
function nearMe(button, resultEl, opts) {
if (!button || !resultEl) return;
opts = opts || {};
if (!navigator.geolocation) {
button.disabled = true;
resultEl.innerHTML = '<p class="at-near-msg">' + esc(t('map.noGeo')) + '</p>';
return;
}
button.addEventListener('click', function () {
button.disabled = true;
resultEl.hidden = false;
resultEl.innerHTML = '<p class="at-near-msg">' + esc(t('map.locating')) + '</p>';
navigator.geolocation.getCurrentPosition(function (pos) {
var me = [pos.coords.longitude, pos.coords.latitude];
Promise.all([stops(opts), stationList(opts)]).then(function (res) {
var items = [];
res[0].forEach(function (s) {
var pt = pointOf(s);
if (pt) items.push({ kind: 'stop', o: s, pt: pt, d: hav(me, pt) });
});
res[1].forEach(function (s) {
var pt = pointOf(s);
if (pt) items.push({ kind: 'station', o: s, pt: pt, d: hav(me, pt) });
});
items.sort(function (a, b) { return a.d - b.d; });
var near = items.slice(0, opts.limit || 8);
renderNear(resultEl, near, me, opts);
/* ปลดล็อกปุ่มหลังหาป้ายเสร็จ — ผู้ใช้เดินไปที่ใหม่แล้วกดซ้ำได้ */
button.disabled = false;
});
}, function () {
button.disabled = false;
resultEl.innerHTML = '<p class="at-near-msg at-near-err">' + esc(t('map.geoDenied')) + '</p>';
}, { enableHighAccuracy: true, timeout: 10000, maximumAge: 60000 });
});
}
function renderNear(host, near, me, opts) {
host.hidden = false;
host.innerHTML = '';
var box = document.createElement('div');
box.className = 'at-map';
box.id = 'near-me-map';
host.appendChild(box);
var cap = document.createElement('p');
cap.className = 'at-map-caption';
cap.textContent = t('map.nearestTitle');
host.appendChild(cap);
var ul = document.createElement('ul');
ul.className = 'at-near-list';
near.forEach(function (x) {
var li = document.createElement('li');
var name = x.kind === 'station' ? x.o.station_name_th : (x.o.place || x.o.type);
var meta = [];
if (x.kind === 'station') meta.push(t('map.legendTerminal'));
else {
if (x.o.kilometer) meta.push(t('map.km') + ' ' + x.o.kilometer);
if (x.o.position) meta.push(x.o.position);
if (x.o.type && x.o.place) meta.push(x.o.type);
}
var bl = x.o['buses-line'] || [];
if (bl.length) meta.push(t('map.servedBy') + ' ' + bl.join(', '));
var link = document.createElement('a');
link.className = 'at-near-row';
link.href = x.kind === 'station' ? href(opts, x.o.station_code) : mapsLink(x.o.latitude, x.o.longitude);
if (x.kind === 'stop') { link.target = '_blank'; link.rel = 'noopener'; }
link.innerHTML = '<span class="at-near-name">' + esc(name || t('map.legendStop')) + '</span>' +
'<span class="at-near-meta">' + esc(meta.join(' · ')) + '</span>' +
'<span class="at-near-dist">' + (x.d < 1000 ? Math.round(x.d) + ' ' + esc(t('map.mUnit')) : (x.d / 1000).toFixed(1) + ' ' + esc(t('map.km'))) + '</span>';
li.appendChild(link);
ul.appendChild(li);
});
host.appendChild(ul);
drawNearMap(box, near, me);
}
function drawNearMap(box, near, me) {
var offline = navigator.onLine === 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');
L.marker([me[1], me[0]], { icon: L.divIcon({ className: 'at-pin-wrap', html: '<span class="at-pin here"></span>', iconSize: [18, 18], iconAnchor: [9, 9] }) })
.bindTooltip(esc(t('map.youAreHere')), { direction: 'top', offset: [0, -11] }).addTo(map);
var pts = [[me[1], me[0]]];
near.forEach(function (x) {
var kind = x.kind === 'station' ? 'term' : 'stop';
L.marker([x.pt[1], x.pt[0]], { icon: pinIcon(kind) })
.bindTooltip(esc(x.kind === 'station' ? x.o.station_name_th : (x.o.place || x.o.type)), { direction: 'top', offset: [0, -8] })
.addTo(map);
pts.push([x.pt[1], x.pt[0]]);
});
map.fitBounds(L.latLngBounds(pts), { padding: [28, 28] });
}
/* ---------- แผนที่ "เส้นทางที่เสนอ" (ยังไม่มีจริง — วาดจากโครงข้อมูลที่ผู้ใช้กำหนด) ----------
spec = { origin:{lat,lng,label}, routes:[{ id, line_color, line_name,
dest:{name,lat,lng}, via:[{name,lat,lng}] }] }
เส้นที่ยังไม่ใส่พิกัดปลายทาง = ข้ามการวาด (ไปโผล่ในรายการฝั่งผู้เรียกแทน)
onPick(route) เรียกเมื่อคลิกเส้น/จุด — ผู้เรียกเป็นคนแสดงรายละเอียดเอง */
/* อ่านพิกัดจากได้ทั้ง 2 แบบ: coords = [lat, lng] (แบบใหม่) หรือ lat/lng แยก (แบบเดิม) */
function coordOf(o) {
o = o || {};
if (Array.isArray(o.coords) && o.coords.length >= 2) {
var a = num(o.coords[0]), b = num(o.coords[1]);
return (a == null || b == null) ? null : [a, b];
}
var la = num(o.lat), ln = num(o.lng);
return (la == null || ln == null) ? null : [la, ln];
}
function proposal(el, spec, onPick) {
var mk = makeMap(el), map = mk.map;
var group = L.featureGroup().addTo(map);
var pts = [];
var o = spec.origin || {};
var org = coordOf(o);
if (!org) { return { map: map, empty: true }; }
pts.push(org);
L.circleMarker(org, { radius: 8, color: '#fff', weight: 3, fillColor: '#1f2a44', fillOpacity: 1 })
.bindTooltip(esc(o.label || t('map.originShort')), { permanent: true, direction: 'top', offset: [0, -8], className: 'at-tip-org' })
.addTo(group);
var pending = []; /* เส้นที่พิกัดปลายทางมาจาก geojson (โหลด async) */
(spec.routes || []).forEach(function (r) {
var d = r.dest || {};
if (r.geo_id) { /* มีไฟล์เส้นทาง → โหลดเพื่อวาดเส้นจริง */
pending.push(loadGeo(r.geo_id, spec).then(function (geo) {
var ls = flatten(geo);
r.__shape = toLatLngs(ls); /* ★ เส้นจริงจาก geojson (วาดตามที่ลากใน QGIS) */
if (!coordOf(d)) { /* dest ยังไม่มีพิกัด → เดาจากจุดไกลสุดของเส้น */
var ps = [];
ls.forEach(function (l) { if (l && l.length) { ps.push(l[0]); ps.push(l[l.length - 1]); } });
if (!ps.length) return;
var ref = ps[0], far = ps[0], best = -1;
ps.forEach(function (pt) {
var dd = Math.pow(num(pt[0]) - num(ref[0]), 2) + Math.pow(num(pt[1]) - num(ref[1]), 2);
if (dd > best) { best = dd; far = pt; }
});
d.coords = [num(far[1]), num(far[0])]; /* geojson = [lng, lat] → [lat, lng] */
}
r.__geoOk = true;
}).catch(function () { /* อ่านไม่ได้ → ใช้ coords ที่มี (ถ้ามี) */ }));
}
});
var drawAll = function () {
(spec.routes || []).forEach(function (r) {
var d = r.dest || {};
var dl = coordOf(d);
if (!dl) return; /* ยังไม่มีพิกัด → ข้าม */
var col = r.line_color || '#7a4cc0';
/* เส้นจริงจาก geojson (ถ้ามี) → วาดตามเส้นที่ลากไว้ · ไม่มี → เส้นตรงต้นทาง→ปลายทาง + จุดแวะ */
var segs = (r.__shape && r.__shape.length) ? r.__shape : [[org].concat(
(r.via || []).map(coordOf).filter(Boolean), dl)];
/* smoothFactor 0.5 = ลดจุดน้อยลง (ค่าเริ่มต้น Leaflet = 1.0 ทำให้เส้นดูตรงตอนซูมออก) */
var line = L.featureGroup(segs.map(function (seg) {
return L.polyline(seg, { color: col, weight: 4, opacity: .85, dashArray: '10 8', smoothFactor: 0.5 });
})).addTo(group);
/* FeatureGroup ไม่มี setStyle → แนบ helper ให้ผู้เรียกใช้ได้เหมือน polyline เดี่ยว */
line.setStyle = function (st) { this.eachLayer(function (l) { l.setStyle(st); }); return this; };
var dot = L.circleMarker(dl, { radius: 7, color: '#fff', weight: 2, fillColor: col, fillOpacity: 1 })
.bindTooltip(esc(d.name || ''), { direction: 'top', offset: [0, -6] }).addTo(group);
pts.push(dl);
function pick(e) {
if (e && e.originalEvent) L.DomEvent.stopPropagation(e);
if (onPick) onPick(r, { line: line, dot: dot });
}
line.on('click', pick);
dot.on('click', pick);
r.__layer = { line: line, dot: dot }; /* ให้ผู้เรียกไฮไลต์ได้ */
});
};
/* มีเส้นที่ต้องอ่านพิกัดจาก geojson → รอให้ครบก่อนวาด · ไม่มี → วาดเลย */
(pending.length ? Promise.all(pending) : Promise.resolve()).then(function () {
drawAll();
fitAll(map, pts);
setTimeout(function () { map.invalidateSize(); }, 60);
});
return { map: map, group: group };
}
return {
route: route, forStop: forStop, proposal: proposal, nearMe: nearMe,
NEAR_M: NEAR_M, LINE_MAIN: LINE_MAIN,
maps: MAPS /* ไว้ตรวจสอบ/ทดสอบจากคอนโซล */
};
})();