.geojson เส้นทางจริงจาก QGIS (WGS84)
busstop_list.json 154 ป้าย (มีพิกัด + buses-line)
stations.json 19 สถานีของเรา (13 มีพิกัด)
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 = '© 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, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, ''');
}
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) {
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, 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] });
}
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) { 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('กม. ' + s.kilometer);
if (s.position) short.push(s.position);
if (s.type) short.push(s.type);
var html = '';
html += '
' + esc(s.place || s.type || t('map.legendStop')) + '';
var meta = [];
if (s.kilometer) meta.push('กม. ' + s.kilometer);
if (s.position) meta.push(s.position);
if (s.type && s.place) meta.push(s.type); /* ซ้ำกับหัวข้อเมื่อไม่มีชื่อสถานที่ */
if (meta.length) html += '
' + esc(meta.join(' · ')) + '';
var bl = s['buses-line'] || [];
if (bl.length) html += '
' + esc(t('map.servedBy')) + ': ' + esc(bl.join(', ')) + '';
html += '
' + esc(t('map.openInMaps')) + '';
html += '
';
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);
});
}
/* สถานีของเรา: ชื่อ + คลิกไปหน้ารายละเอียดป้าย (opts.stopHref) */
function drawStations(map, hits, opts, group) {
hits.forEach(function (h) {
var s = h.station, pt = pointOf(s);
if (!pt) return;
var html = '' + esc(s.station_name_th) + '';
html += '
' + esc([s.city_th, s.province_th].filter(Boolean).join(' · ')) + '';
if (s.station_code) html += '
' + esc(t('map.viewStopPage')) + '';
html += '
';
L.marker([pt[1], pt[0]], { icon: pinIcon('term') })
.bindTooltip('' + esc(s.station_name_th) + '
' + esc(s.province_th || ''), { direction: 'top', offset: [0, -9] })
.bindPopup(html, { closeButton: false, offset: [0, -6] })
.addTo(group);
});
}
function stationsNear(lines, maxM, o) {
return stationList(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 > 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');
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) + '' +
'' + val + '';
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, '' + esc(t('map.empty')) + '');
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), 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 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 (rows.length) parts.push(esc(t('map.stations')) + ' ' + rows.length + '');
if (m.offline) parts.push('' + esc(t('map.offline')) + '');
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') }
]);
});
}
/* ============================================================
#/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, '' + esc(t(st ? 'map.noRoutesHere' : 'map.empty')) + '');
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, '' + esc(t('map.empty')) + '');
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('' + esc(pinName) + '
' + 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('' + esc(t('map.offline')) + '');
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 = '' + esc(t('map.noGeo')) + '
';
return;
}
button.addEventListener('click', function () {
button.disabled = true;
resultEl.hidden = false;
resultEl.innerHTML = '' + esc(t('map.locating')) + '
';
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);
});
}, function () {
button.disabled = false;
resultEl.innerHTML = '' + esc(t('map.geoDenied')) + '
';
}, { 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('กม. ' + 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 = '' + esc(name || t('map.legendStop')) + '' +
'' + esc(meta.join(' · ')) + '' +
'' + (x.d < 1000 ? Math.round(x.d) + ' ม.' : (x.d / 1000).toFixed(1) + ' ' + esc(t('map.km'))) + '';
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: '', 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] });
}
return {
route: route, forStop: forStop, nearMe: nearMe,
NEAR_M: NEAR_M, LINE_MAIN: LINE_MAIN,
maps: MAPS /* ไว้ตรวจสอบ/ทดสอบจากคอนโซล */
};
})();