const state = { map: null, mapProvider: "", markers: new Map(), infoOverlay: null, routeOverlay: null, routeDestinationOverlay: null, markerAnimationMs: 900, drivers: new Map(), locations: new Map(), selectedDriverId: "", eventSource: null, activeView: "locations", adminToken: new URLSearchParams(window.location.search).get("adminToken") || window.localStorage.getItem("cargoRadarAdminToken") || "" }; const elements = { connectionStatus: document.getElementById("connectionStatus"), refreshButton: document.getElementById("refreshButton"), demoButton: document.getElementById("demoButton"), locationsTab: document.getElementById("locationsTab"), driversTab: document.getElementById("driversTab"), locationsPanel: document.getElementById("locationsPanel"), driversPanel: document.getElementById("driversPanel"), vehicleList: document.getElementById("vehicleList"), mapMessage: document.getElementById("mapMessage"), totalCount: document.getElementById("totalCount"), activeCount: document.getElementById("activeCount"), staleCount: document.getElementById("staleCount"), lastUpdated: document.getElementById("lastUpdated"), driverForm: document.getElementById("driverForm"), driverNameInput: document.getElementById("driverNameInput"), vehicleNoInput: document.getElementById("vehicleNoInput"), vehicleTypeInput: document.getElementById("vehicleTypeInput"), phoneInput: document.getElementById("phoneInput"), driverIdInput: document.getElementById("driverIdInput"), driverCount: document.getElementById("driverCount"), driverList: document.getElementById("driverList"), historyDrawer: document.getElementById("historyDrawer"), historyCloseButton: document.getElementById("historyCloseButton"), historyTitle: document.getElementById("historyTitle"), historySummary: document.getElementById("historySummary"), historyList: document.getElementById("historyList") }; const VEHICLE_TYPES = { "cargo-truck": { label: "카고트럭", shortLabel: "카고", className: "type-cargo" }, "tractor-trailer": { label: "트레일러", shortLabel: "트레", className: "type-trailer" }, "box-truck": { label: "탑차", shortLabel: "탑차", className: "type-box" }, "van": { label: "용달차", shortLabel: "용달", className: "type-van" }, "refrigerated": { label: "냉동탑차", shortLabel: "냉동", className: "type-cold" }, "container": { label: "컨테이너", shortLabel: "컨", className: "type-container" }, "wingbody": { label: "윙바디", shortLabel: "윙", className: "type-wing" } }; document.addEventListener("DOMContentLoaded", () => { initializeMap(); bindActions(); refreshDrivers(); refreshLatestLocations(); connectEvents(); }); async function initializeMap() { const kakaoJavaScriptKey = window.CARGORADAR_CONFIG?.kakaoJavaScriptKey || ""; if (kakaoJavaScriptKey) { try { await loadKakaoMapsSdk(kakaoJavaScriptKey); const center = new kakao.maps.LatLng(36.45, 127.85); state.map = new kakao.maps.Map(document.getElementById("map"), { center, level: 13 }); state.mapProvider = "kakao"; state.map.addControl(new kakao.maps.ZoomControl(), kakao.maps.ControlPosition.RIGHT); state.map.addControl(new kakao.maps.MapTypeControl(), kakao.maps.ControlPosition.TOPRIGHT); hideMapMessage(); updateMarkers({ fitBounds: state.locations.size > 0 }); return; } catch (error) { console.warn("Kakao map unavailable. Falling back to OpenStreetMap.", error); } } try { await initializeLeafletMap(); } catch (error) { console.error(error); showMapMessage("지도 로딩에 실패했습니다. 네트워크 상태를 확인하세요."); } } function loadKakaoMapsSdk(appKey) { return new Promise((resolve, reject) => { if (window.kakao?.maps) { kakao.maps.load(resolve); return; } const script = document.createElement("script"); script.src = `https://dapi.kakao.com/v2/maps/sdk.js?appkey=${encodeURIComponent(appKey)}&autoload=false`; script.async = true; script.onload = () => { if (!window.kakao?.maps) { reject(new Error("kakao_maps_not_authorized")); return; } kakao.maps.load(resolve); }; script.onerror = () => reject(new Error("kakao_maps_load_failed")); document.head.appendChild(script); }); } async function initializeLeafletMap() { await loadLeafletAssets(); state.mapProvider = "leaflet"; state.map = L.map("map", { attributionControl: true, zoomControl: true }).setView([36.45, 127.85], 7); L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { maxZoom: 19, attribution: '© OpenStreetMap contributors' }).addTo(state.map); showMapMessage("카카오맵 권한 전까지 OpenStreetMap으로 표시 중"); window.setTimeout(hideMapMessage, 4500); updateMarkers({ fitBounds: state.locations.size > 0 }); } function loadLeafletAssets() { if (window.L?.map) return Promise.resolve(); const version = "1.9.4"; const stylesheet = loadStylesheet( "leaflet-stylesheet", `https://unpkg.com/leaflet@${version}/dist/leaflet.css` ); const script = loadScript( "leaflet-script", `https://unpkg.com/leaflet@${version}/dist/leaflet.js` ); return Promise.all([stylesheet, script]).then(() => { if (!window.L?.map) throw new Error("leaflet_load_failed"); }); } function loadStylesheet(id, href) { return new Promise((resolve, reject) => { if (document.getElementById(id)) { resolve(); return; } const link = document.createElement("link"); link.id = id; link.rel = "stylesheet"; link.href = href; link.onload = resolve; link.onerror = () => reject(new Error(`${id}_load_failed`)); document.head.appendChild(link); }); } function loadScript(id, src) { return new Promise((resolve, reject) => { if (document.getElementById(id)) { resolve(); return; } const script = document.createElement("script"); script.id = id; script.src = src; script.async = true; script.onload = resolve; script.onerror = () => reject(new Error(`${id}_load_failed`)); document.head.appendChild(script); }); } function bindActions() { elements.refreshButton.addEventListener("click", refreshLatestLocations); elements.demoButton.addEventListener("click", postDemoLocation); elements.locationsTab.addEventListener("click", () => setActiveView("locations")); elements.driversTab.addEventListener("click", () => setActiveView("drivers")); elements.driverForm.addEventListener("submit", submitDriverForm); elements.historyCloseButton.addEventListener("click", closeHistoryDrawer); } function setActiveView(view) { state.activeView = view; elements.locationsTab.classList.toggle("is-active", view === "locations"); elements.driversTab.classList.toggle("is-active", view === "drivers"); elements.locationsPanel.classList.toggle("is-hidden", view !== "locations"); elements.driversPanel.classList.toggle("is-hidden", view !== "drivers"); } async function refreshLatestLocations() { try { setConnectionStatus("연결됨", "online"); const data = await fetchJson("/api/v1/locations/latest", { headers: adminHeaders() }); replaceLocations(data.locations || []); } catch (error) { console.error(error); if (error.message === "invalid_admin_token") { requestAdminToken(); return; } setConnectionStatus("조회 실패", "error"); } } async function refreshDrivers() { try { const data = await fetchJson("/api/v1/drivers", { headers: adminHeaders() }); replaceDrivers(data.drivers || []); } catch (error) { console.error(error); if (error.message === "invalid_admin_token") { requestAdminToken(); } } } function connectEvents() { if (state.eventSource) { state.eventSource.close(); } state.eventSource = new EventSource(withAdminToken("/api/v1/events")); state.eventSource.addEventListener("open", () => setConnectionStatus("실시간 연결", "online")); state.eventSource.addEventListener("snapshot", (event) => { const payload = JSON.parse(event.data); replaceLocations(payload.locations || []); }); state.eventSource.addEventListener("location.updated", (event) => { const location = JSON.parse(event.data); upsertLocation(location, { focus: state.selectedDriverId === location.driverId }); }); state.eventSource.addEventListener("drivers.updated", (event) => { const payload = JSON.parse(event.data); replaceDrivers(payload.drivers || []); }); state.eventSource.addEventListener("error", () => setConnectionStatus("재연결 중", "error")); } async function postDemoLocation() { const driver = getDemoDriver(); const now = Date.now(); const latitude = 37.5665 + Math.sin(now / 60000) * 0.03; const longitude = 126.978 + Math.cos(now / 60000) * 0.04; try { await fetchJson("/api/v1/locations", { method: "POST", headers: { "Content-Type": "application/json", "X-Device-Token": driver.token }, body: JSON.stringify({ driverId: driver.driverId, vehicleNo: driver.vehicleNo, vehicleType: driver.vehicleType || "cargo-truck", latitude, longitude, accuracy: 12, speed: 42, heading: Math.round((now / 1000) % 360), cargoName: "전자부품", cargoQuantity: "36박스", cargoWeight: "1.2t", origin: "서울 상차지", destination: "평택 물류센터", provider: "demo", recordedAt: new Date().toISOString() }) }); } catch (error) { console.error(error); setConnectionStatus("전송 실패", "error"); } } function getDemoDriver() { const enabledDriver = [...state.drivers.values()].find((driver) => driver.enabled && driver.token); return enabledDriver || { driverId: "demo-driver", vehicleNo: "SEOUL-12-3456", token: "demo-token" }; } function replaceLocations(locations) { state.locations.clear(); for (const location of locations) { state.locations.set(location.driverId, location); } render(); updateMarkers({ fitBounds: locations.length > 0 }); if (state.selectedDriverId) { const selectedLocation = state.locations.get(state.selectedDriverId); if (selectedLocation) { renderRoutePreview(selectedLocation, { fit: false }); showInfoOverlay(selectedLocation); } else { clearRouteOverlay(); } } } function replaceDrivers(drivers) { state.drivers.clear(); for (const driver of drivers) { state.drivers.set(driver.driverId, driver); } renderDrivers(); } function upsertLocation(location, options = {}) { state.locations.set(location.driverId, location); render(); updateMarker(location); if (state.selectedDriverId === location.driverId && !elements.historyDrawer.classList.contains("is-hidden")) { loadLocationHistory(location); renderRoutePreview(location, { fit: false }); showInfoOverlay(location); } if (options.focus) { fitMapToRoute(location) || centerMapOnLocation(location); } } function render() { const locations = [...state.locations.values()].sort((left, right) => { return new Date(right.receivedAt).getTime() - new Date(left.receivedAt).getTime(); }); const counts = locations.reduce( (accumulator, location) => { const status = getLocationStatus(location); accumulator.total += 1; if (status.key === "active") accumulator.active += 1; if (status.key !== "active") accumulator.stale += 1; return accumulator; }, { total: 0, active: 0, stale: 0 } ); elements.totalCount.textContent = String(counts.total); elements.activeCount.textContent = String(counts.active); elements.staleCount.textContent = String(counts.stale); elements.lastUpdated.textContent = locations[0] ? formatDateTime(locations[0].receivedAt) : "-"; elements.vehicleList.replaceChildren(); if (!locations.length) { const empty = document.createElement("div"); empty.className = "empty-state"; empty.textContent = "수신된 차량 위치가 없습니다."; elements.vehicleList.append(empty); return; } for (const location of locations) { elements.vehicleList.append(createVehicleItem(location)); } } function renderDrivers() { const drivers = [...state.drivers.values()].sort((left, right) => { return String(left.vehicleNo || left.driverId).localeCompare(String(right.vehicleNo || right.driverId), "ko"); }); elements.driverCount.textContent = `${drivers.length}명`; elements.driverList.replaceChildren(); if (!drivers.length) { const empty = document.createElement("div"); empty.className = "empty-state"; empty.textContent = "등록된 기사가 없습니다."; elements.driverList.append(empty); return; } for (const driver of drivers) { elements.driverList.append(createDriverItem(driver)); } } function createVehicleItem(location) { const status = getLocationStatus(location); const vehicleType = getVehicleType(location); const item = document.createElement("article"); item.className = "vehicle-item"; item.tabIndex = 0; const main = document.createElement("div"); main.className = "vehicle-main"; const title = document.createElement("div"); title.className = "vehicle-title"; const badge = document.createElement("span"); badge.className = `badge ${status.key}`; badge.textContent = status.label; const typeBadge = document.createElement("span"); typeBadge.className = `vehicle-type-chip ${vehicleType.className}`; typeBadge.textContent = vehicleType.label; const vehicleNo = document.createElement("strong"); vehicleNo.textContent = location.vehicleNo || location.driverId; title.append(badge, typeBadge, vehicleNo); const meta = document.createElement("div"); meta.className = "vehicle-meta"; meta.textContent = [ location.driverName || location.driverId, getCargoSummary(location), getRouteSummary(location), getRouteProgressSummary(location), formatDateTime(location.receivedAt) ].filter(Boolean).join(" · "); const speed = document.createElement("div"); speed.className = "speed"; speed.textContent = location.speed === null || location.speed === undefined ? "-" : `${Math.round(location.speed)} km/h`; main.append(title, meta); item.append(main, speed); item.addEventListener("click", () => focusLocation(location)); item.addEventListener("keydown", (event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); focusLocation(location); } }); return item; } function createDriverItem(driver) { const vehicleType = getVehicleType(driver); const item = document.createElement("article"); item.className = "driver-item"; const head = document.createElement("div"); head.className = "driver-head"; const title = document.createElement("div"); title.className = "driver-title"; const name = document.createElement("strong"); name.textContent = `${driver.vehicleNo || driver.driverId} · ${driver.name}`; const meta = document.createElement("div"); meta.className = "vehicle-meta"; meta.textContent = [vehicleType.label, driver.driverId, driver.phone].filter(Boolean).join(" · "); title.append(name, meta); const badge = document.createElement("span"); badge.className = `badge ${driver.enabled ? "active" : "offline"}`; badge.textContent = driver.enabled ? "사용" : "중지"; head.append(title, badge); const tokenRow = document.createElement("div"); tokenRow.className = "driver-token"; const token = document.createElement("code"); token.textContent = driver.token || "-"; const copyButton = document.createElement("button"); copyButton.type = "button"; copyButton.textContent = "복사"; copyButton.addEventListener("click", () => copyToken(driver.token)); tokenRow.append(token, copyButton); const actions = document.createElement("div"); actions.className = "driver-actions"; const toggleButton = document.createElement("button"); toggleButton.type = "button"; toggleButton.textContent = driver.enabled ? "중지" : "사용"; toggleButton.addEventListener("click", () => updateDriver(driver.driverId, { enabled: !driver.enabled })); const tokenButton = document.createElement("button"); tokenButton.type = "button"; tokenButton.textContent = "토큰 재발급"; tokenButton.addEventListener("click", () => updateDriver(driver.driverId, { regenerateToken: true })); const deleteButton = document.createElement("button"); deleteButton.type = "button"; deleteButton.textContent = "삭제"; deleteButton.addEventListener("click", () => deleteDriver(driver)); actions.append(toggleButton, tokenButton, deleteButton); item.append(head, tokenRow, actions); return item; } async function submitDriverForm(event) { event.preventDefault(); const payload = { name: elements.driverNameInput.value.trim(), vehicleNo: elements.vehicleNoInput.value.trim(), vehicleType: elements.vehicleTypeInput.value, phone: elements.phoneInput.value.trim(), driverId: elements.driverIdInput.value.trim() }; try { await fetchJson("/api/v1/drivers", { method: "POST", headers: { "Content-Type": "application/json", ...adminHeaders() }, body: JSON.stringify(payload) }); elements.driverForm.reset(); await refreshDrivers(); } catch (error) { console.error(error); window.alert(`등록 실패: ${error.message}`); } } async function updateDriver(driverId, patch) { try { const data = await fetchJson(`/api/v1/drivers/${encodeURIComponent(driverId)}`, { method: "PATCH", headers: { "Content-Type": "application/json", ...adminHeaders() }, body: JSON.stringify(patch) }); state.drivers.set(data.driver.driverId, data.driver); renderDrivers(); } catch (error) { console.error(error); window.alert(`수정 실패: ${error.message}`); } } async function deleteDriver(driver) { const confirmed = window.confirm(`${driver.vehicleNo || driver.driverId} 삭제`); if (!confirmed) return; try { await fetchJson(`/api/v1/drivers/${encodeURIComponent(driver.driverId)}`, { method: "DELETE", headers: adminHeaders() }); state.drivers.delete(driver.driverId); renderDrivers(); } catch (error) { console.error(error); window.alert(`삭제 실패: ${error.message}`); } } async function copyToken(token) { if (!token) return; try { await navigator.clipboard.writeText(token); setConnectionStatus("토큰 복사됨", "online"); } catch { window.prompt("기기 토큰", token); } } function updateMarkers({ fitBounds = false } = {}) { if (!state.map || !state.mapProvider) return; const activeIds = new Set(state.locations.keys()); for (const [driverId, marker] of state.markers) { if (!activeIds.has(driverId)) { removeMarker(marker); state.markers.delete(driverId); } } for (const location of state.locations.values()) { updateMarker(location); } if (fitBounds && state.markers.size > 0) { fitMapToLocations(); } } function updateMarker(location) { if (!state.map || !state.mapProvider) return; if (state.mapProvider === "leaflet") { updateLeafletMarker(location); return; } updateKakaoMarker(location); } function updateKakaoMarker(location) { const targetPosition = createPosition(location.latitude, location.longitude); const kakaoPosition = new kakao.maps.LatLng(targetPosition.latitude, targetPosition.longitude); const status = getLocationStatus(location); const markerElement = createTruckMarkerElement(location, status); let marker = state.markers.get(location.driverId); if (!marker) { marker = { provider: "kakao", overlay: new kakao.maps.CustomOverlay({ position: kakaoPosition, content: markerElement, yAnchor: 1 }), currentPosition: targetPosition }; marker.overlay.setMap(state.map); state.markers.set(location.driverId, marker); } else { marker.overlay.setContent(markerElement); animateMarkerPosition(marker, targetPosition); } } function updateLeafletMarker(location) { const status = getLocationStatus(location); const vehicleType = getVehicleType(location); const targetPosition = createPosition(location.latitude, location.longitude); const leafletPosition = [targetPosition.latitude, targetPosition.longitude]; const icon = L.divIcon({ className: `leaflet-truck-marker truck-marker ${status.key} ${vehicleType.className}`, html: createTruckMarkerHtml(location, vehicleType), iconSize: [74, 38], iconAnchor: [37, 38], popupAnchor: [0, -30] }); let marker = state.markers.get(location.driverId); if (!marker) { marker = { provider: "leaflet", marker: L.marker(leafletPosition, { icon, title: location.vehicleNo || location.driverId }), currentPosition: targetPosition }; marker.marker.on("click", () => focusLocation(location)); marker.marker.addTo(state.map); state.markers.set(location.driverId, marker); } else { marker.marker.setIcon(icon); marker.marker.off("click"); marker.marker.on("click", () => focusLocation(location)); animateMarkerPosition(marker, targetPosition); } } function createTruckMarkerElement(location, status) { const vehicleType = getVehicleType(location); const markerElement = document.createElement("button"); markerElement.className = `truck-marker ${status.key} ${vehicleType.className}`; markerElement.type = "button"; markerElement.title = `${vehicleType.label} ${location.vehicleNo || location.driverId}`; markerElement.setAttribute("aria-label", `${vehicleType.label} ${location.vehicleNo || location.driverId} 위치 보기`); markerElement.innerHTML = createTruckMarkerHtml(location, vehicleType); markerElement.addEventListener("click", () => focusLocation(location)); return markerElement; } function createTruckMarkerHtml(location, vehicleType = getVehicleType(location)) { const label = location.vehicleNo ? location.vehicleNo.slice(-4) : location.driverId.slice(0, 4); return ` ${escapeHtml(vehicleType.shortLabel)} ${escapeHtml(label)} `; } function animateMarkerPosition(marker, targetPosition) { const fromPosition = marker.currentPosition || getMarkerPosition(marker) || targetPosition; if (calculateDistanceKm(fromPosition, targetPosition) < 0.01) { setMarkerPosition(marker, targetPosition); marker.currentPosition = targetPosition; return; } cancelMarkerAnimation(marker); const startedAt = window.performance.now(); const duration = state.markerAnimationMs; const tick = (timestamp) => { const progress = Math.min(1, (timestamp - startedAt) / duration); const easedProgress = easeInOutCubic(progress); const nextPosition = { latitude: interpolateNumber(fromPosition.latitude, targetPosition.latitude, easedProgress), longitude: interpolateNumber(fromPosition.longitude, targetPosition.longitude, easedProgress) }; setMarkerPosition(marker, nextPosition); marker.currentPosition = nextPosition; if (progress < 1) { marker.animationFrame = window.requestAnimationFrame(tick); } else { marker.animationFrame = null; marker.currentPosition = targetPosition; setMarkerPosition(marker, targetPosition); } }; marker.animationFrame = window.requestAnimationFrame(tick); } function cancelMarkerAnimation(marker) { if (!marker?.animationFrame) return; window.cancelAnimationFrame(marker.animationFrame); marker.animationFrame = null; } function getMarkerPosition(marker) { if (marker.provider === "leaflet" && marker.marker?.getLatLng) { const position = marker.marker.getLatLng(); return createPosition(position.lat, position.lng); } return marker.currentPosition || null; } function setMarkerPosition(marker, position) { if (marker.provider === "kakao") { marker.overlay.setPosition(new kakao.maps.LatLng(position.latitude, position.longitude)); return; } if (marker.provider === "leaflet") { marker.marker.setLatLng([position.latitude, position.longitude]); } } function createPosition(latitude, longitude) { return { latitude: Number(latitude), longitude: Number(longitude) }; } function easeInOutCubic(value) { return value < 0.5 ? 4 * value * value * value : 1 - ((-2 * value + 2) ** 3) / 2; } function removeMarker(marker) { cancelMarkerAnimation(marker); if (marker.provider === "kakao") { marker.overlay.setMap(null); return; } if (marker.provider === "leaflet") { marker.marker.remove(); } } function fitMapToLocations() { if (state.mapProvider === "kakao") { const bounds = new kakao.maps.LatLngBounds(); for (const location of state.locations.values()) { bounds.extend(new kakao.maps.LatLng(location.latitude, location.longitude)); } state.map.setBounds(bounds); return; } if (state.mapProvider === "leaflet") { const bounds = L.latLngBounds([...state.locations.values()].map((location) => { return [location.latitude, location.longitude]; })); state.map.fitBounds(bounds, { maxZoom: 14, padding: [40, 40] }); } } function centerMapOnLocation(location, options = {}) { if (!state.map || !state.mapProvider) return; if (state.mapProvider === "kakao") { const position = new kakao.maps.LatLng(location.latitude, location.longitude); state.map.setCenter(position); if (options.zoom && state.map.getLevel() > 4) { state.map.setLevel(4); } return; } if (state.mapProvider === "leaflet") { const nextZoom = options.zoom ? Math.max(state.map.getZoom(), 14) : state.map.getZoom(); state.map.setView([location.latitude, location.longitude], nextZoom, { animate: true }); } } function renderRoutePreview(location, options = {}) { clearRouteOverlay(); const routePath = getRoutePath(location); if (routePath.length < 2) return false; if (state.mapProvider === "kakao") { const path = routePath.map((point) => new kakao.maps.LatLng(point.latitude, point.longitude)); state.routeOverlay = new kakao.maps.Polyline({ path, strokeWeight: 5, strokeColor: "#1f6feb", strokeOpacity: 0.86, strokeStyle: "solid" }); state.routeOverlay.setMap(state.map); state.routeDestinationOverlay = new kakao.maps.CustomOverlay({ position: path[path.length - 1], content: createDestinationMarkerElement(location), yAnchor: 1.1 }); state.routeDestinationOverlay.setMap(state.map); } if (state.mapProvider === "leaflet") { const path = routePath.map((point) => [point.latitude, point.longitude]); state.routeOverlay = L.polyline(path, { color: "#1f6feb", weight: 5, opacity: 0.86, lineCap: "round", lineJoin: "round" }).addTo(state.map); state.routeDestinationOverlay = L.marker(path[path.length - 1], { icon: L.divIcon({ className: "route-destination-leaflet", html: createDestinationMarkerHtml(location), iconSize: [116, 42], iconAnchor: [58, 42] }) }).addTo(state.map); } if (options.fit !== false) { fitMapToRoute(location); } return true; } function clearRouteOverlay() { if (state.routeOverlay) { if (typeof state.routeOverlay.setMap === "function") { state.routeOverlay.setMap(null); } else if (typeof state.routeOverlay.remove === "function") { state.routeOverlay.remove(); } } if (state.routeDestinationOverlay) { if (typeof state.routeDestinationOverlay.setMap === "function") { state.routeDestinationOverlay.setMap(null); } else if (typeof state.routeDestinationOverlay.remove === "function") { state.routeDestinationOverlay.remove(); } } state.routeOverlay = null; state.routeDestinationOverlay = null; } function fitMapToRoute(location) { const routePath = getRoutePath(location); if (!state.map || !state.mapProvider || routePath.length < 2) return false; if (state.mapProvider === "kakao") { const bounds = new kakao.maps.LatLngBounds(); for (const point of routePath) { bounds.extend(new kakao.maps.LatLng(point.latitude, point.longitude)); } state.map.setBounds(bounds); return true; } if (state.mapProvider === "leaflet") { state.map.fitBounds( L.latLngBounds(routePath.map((point) => [point.latitude, point.longitude])), { maxZoom: 13, padding: [48, 48] } ); return true; } return false; } function createDestinationMarkerElement(location) { const marker = document.createElement("div"); marker.className = "route-destination-marker"; marker.innerHTML = createDestinationMarkerHtml(location); return marker; } function createDestinationMarkerHtml(location) { const metrics = getRouteMetrics(location); const destinationName = getDestinationName(location) || "목적지"; const etaText = metrics ? formatEtaTime(metrics.estimatedArrivalAt) : "ETA"; return ` 도착 ${escapeHtml(destinationName)} ${escapeHtml(etaText)} `; } function focusLocation(location) { loadLocationHistory(location); if (!state.map || !state.mapProvider) return; if (!renderRoutePreview(location, { fit: true })) { centerMapOnLocation(location, { zoom: true }); } showInfoOverlay(location); } async function loadLocationHistory(location) { state.selectedDriverId = location.driverId; elements.historyDrawer.classList.remove("is-hidden"); elements.historyTitle.textContent = `${location.vehicleNo || location.driverId} 위치 이력`; elements.historySummary.textContent = "조회 중"; elements.historyList.replaceChildren(); try { const data = await fetchJson( `/api/v1/locations/history?driverId=${encodeURIComponent(location.driverId)}&limit=80`, { headers: adminHeaders() } ); renderHistory(location, data.locations || []); } catch (error) { console.error(error); elements.historySummary.textContent = `조회 실패: ${error.message}`; } } function renderHistory(location, records) { elements.historyList.replaceChildren(); elements.historySummary.textContent = `${records.length}건 · ${location.driverName || location.driverId}`; if (!records.length) { const empty = document.createElement("div"); empty.className = "empty-state"; empty.textContent = "위치 이력이 없습니다."; elements.historyList.append(empty); return; } for (const record of records.reverse()) { const row = document.createElement("div"); row.className = "history-row"; const time = document.createElement("time"); time.textContent = formatTime(record.receivedAt); const coordinate = document.createElement("span"); coordinate.textContent = `${formatCoordinate(record.latitude)}, ${formatCoordinate(record.longitude)}`; const speed = document.createElement("span"); speed.textContent = record.speed === null || record.speed === undefined ? "-" : `${Math.round(record.speed)} km/h`; row.append(time, coordinate, speed); elements.historyList.append(row); } } function closeHistoryDrawer() { state.selectedDriverId = ""; elements.historyDrawer.classList.add("is-hidden"); clearRouteOverlay(); } function showInfoOverlay(location) { const status = getLocationStatus(location); const content = createPopupElement(location, status); if (state.mapProvider === "leaflet") { state.infoOverlay = L.popup({ closeButton: true, offset: [0, -24] }) .setLatLng([location.latitude, location.longitude]) .setContent(content) .openOn(state.map); return; } const position = new kakao.maps.LatLng(location.latitude, location.longitude); if (!state.infoOverlay) { state.infoOverlay = new kakao.maps.CustomOverlay({ yAnchor: 1.35 }); } state.infoOverlay.setContent(content); state.infoOverlay.setPosition(position); state.infoOverlay.setMap(state.map); } function createPopupElement(location, status) { const vehicleType = getVehicleType(location); const container = document.createElement("div"); container.className = "kakao-popup"; const title = document.createElement("strong"); title.className = "popup-title"; title.textContent = location.vehicleNo || location.driverId; const driver = document.createElement("div"); driver.textContent = `${vehicleType.label} · ${location.driverName || location.driverId} · ${status.label}`; const cargo = document.createElement("div"); cargo.className = "popup-cargo"; cargo.textContent = `제품: ${getCargoName(location) || "미등록"}`; const quantity = document.createElement("div"); quantity.textContent = `수량: ${getCargoQuantity(location) || "미등록"}`; const weight = document.createElement("div"); weight.textContent = `중량: ${getCargoWeight(location) || "미등록"}`; const destination = document.createElement("div"); destination.textContent = getRouteSummary(location); const routeInfo = createRouteInfoElement(location); const receivedAt = document.createElement("div"); receivedAt.textContent = `수신: ${formatDateTime(location.receivedAt)}`; const movement = document.createElement("div"); movement.textContent = `속도: ${formatSpeed(location.speed)}`; container.append(title, driver, cargo, quantity, weight, destination, routeInfo, movement, receivedAt); return container; } function createRouteInfoElement(location) { const routeInfo = document.createElement("div"); routeInfo.className = "popup-route"; const metrics = getRouteMetrics(location); if (!metrics) { routeInfo.textContent = "경로: 목적지 좌표 대기"; return routeInfo; } const source = firstString(location.routeSource, location.routingProvider) || "simulated"; routeInfo.append( createPopupRouteLine("남은 거리", formatDistance(metrics.remainingDistanceKm)), createPopupRouteLine("예상 도착", formatEtaTime(metrics.estimatedArrivalAt)), createPopupRouteLine("소요 시간", formatDuration(metrics.etaMinutes)), createPopupRouteLine("경로", source === "simulated" ? "모의 경로" : source) ); return routeInfo; } function createPopupRouteLine(label, value) { const row = document.createElement("div"); const labelElement = document.createElement("span"); labelElement.textContent = label; const valueElement = document.createElement("strong"); valueElement.textContent = value; row.append(labelElement, valueElement); return row; } async function fetchJson(url, options) { const response = await fetch(url, options); const data = await response.json().catch(() => ({})); if (!response.ok) { throw new Error(data.error || `HTTP ${response.status}`); } return data; } function adminHeaders() { return state.adminToken ? { "X-Admin-Token": state.adminToken } : {}; } function withAdminToken(url) { if (!state.adminToken) return url; const parsedUrl = new URL(url, window.location.origin); parsedUrl.searchParams.set("adminToken", state.adminToken); return `${parsedUrl.pathname}${parsedUrl.search}`; } function requestAdminToken() { const token = window.prompt("관리자 토큰"); if (!token) { setConnectionStatus("토큰 필요", "error"); return; } state.adminToken = token.trim(); window.localStorage.setItem("cargoRadarAdminToken", state.adminToken); refreshDrivers(); refreshLatestLocations(); connectEvents(); } function setConnectionStatus(text, mode) { elements.connectionStatus.textContent = text; elements.connectionStatus.classList.toggle("is-online", mode === "online"); elements.connectionStatus.classList.toggle("is-error", mode === "error"); } function showMapMessage(text) { elements.mapMessage.textContent = text; elements.mapMessage.classList.remove("is-hidden"); } function hideMapMessage() { elements.mapMessage.classList.add("is-hidden"); } function getVehicleType(source) { const key = String(source.vehicleType || "cargo-truck").trim(); return VEHICLE_TYPES[key] || VEHICLE_TYPES["cargo-truck"]; } function getLocationStatus(location) { const receivedAt = new Date(location.receivedAt).getTime(); const ageMs = Date.now() - receivedAt; if (ageMs <= 2 * 60 * 1000) return { key: "active", label: "수신중" }; if (ageMs <= 10 * 60 * 1000) return { key: "stale", label: "지연" }; return { key: "offline", label: "미수신" }; } function formatDateTime(value) { const date = new Date(value); if (Number.isNaN(date.getTime())) return "-"; return new Intl.DateTimeFormat("ko-KR", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" }).format(date); } function formatTime(value) { const date = new Date(value); if (Number.isNaN(date.getTime())) return "-"; return new Intl.DateTimeFormat("ko-KR", { hour: "2-digit", minute: "2-digit", second: "2-digit" }).format(date); } function formatSpeed(value) { if (value === null || value === undefined || value === "") return "-"; const speed = Number(value); if (!Number.isFinite(speed)) return "-"; return `${Math.round(speed)} km/h`; } function formatCoordinate(value) { return Number(value).toFixed(5); } function getCargoSummary(location) { return [getCargoName(location), getCargoQuantity(location), getCargoWeight(location)] .filter(Boolean) .join(" · ") || "미등록"; } function getCargoName(location) { return firstString(location.cargoName, location.cargoItem, location.cargo, location.itemName); } function getCargoQuantity(location) { return firstString(location.cargoQuantity, location.quantity, location.qty, location.count); } function getCargoWeight(location) { return firstString(location.cargoWeight, location.weight); } function getRouteSummary(location) { const origin = firstString(location.origin, location.departure); const destination = firstString(location.destination, location.arrival); if (origin && destination) return `구간: ${origin} -> ${destination}`; if (destination) return `도착지: ${destination}`; if (origin) return `상차지: ${origin}`; return "도착지: 미등록"; } function getRouteProgressSummary(location) { const metrics = getRouteMetrics(location); if (!metrics) return ""; return `남은 ${formatDistance(metrics.remainingDistanceKm)} · ETA ${formatEtaTime(metrics.estimatedArrivalAt)}`; } function getRouteMetrics(location) { const routePath = getRoutePath(location); if (routePath.length < 2) return null; const providedDistance = parseFiniteNumber(location.remainingDistanceKm || location.distanceKm || location.routeDistanceKm); const remainingDistanceKm = providedDistance || calculatePathDistanceKm(routePath); const providedEta = parseFiniteNumber(location.etaMinutes || location.estimatedMinutes || location.remainingMinutes); const speed = Math.max(24, parseFiniteNumber(location.speed) || 52); const etaMinutes = Math.max(2, Math.round(providedEta || (remainingDistanceKm / speed) * 60)); const providedArrival = parseOptionalDate(location.estimatedArrivalAt || location.etaAt || location.arrivalAt); const estimatedArrivalAt = providedArrival || new Date(Date.now() + etaMinutes * 60 * 1000); return { remainingDistanceKm, etaMinutes, estimatedArrivalAt }; } function getRoutePath(location) { const current = normalizeDisplayRoutePoint({ latitude: location.latitude, longitude: location.longitude }); if (!current) return []; const providedPath = normalizeDisplayRoutePath(location.routePath || location.path || location.polyline); const destination = getDestinationCoordinate(location) || (providedPath.length ? providedPath[providedPath.length - 1] : null); if (providedPath.length >= 2) { return ensureRouteEndpoints(providedPath, current, destination); } if (!destination) return []; return createFallbackRoutePath(current, destination, location.driverId || location.vehicleNo || ""); } function ensureRouteEndpoints(routePath, current, destination) { const normalizedPath = [...routePath]; if (calculateDistanceKm(current, normalizedPath[0]) > 0.1) { normalizedPath.unshift(current); } if (destination && calculateDistanceKm(destination, normalizedPath[normalizedPath.length - 1]) > 0.1) { normalizedPath.push(destination); } return normalizedPath; } function getDestinationCoordinate(location) { const latitude = parseFiniteNumber( location.destinationLatitude || location.destinationLat || location.arrivalLatitude || location.arrivalLat ); const longitude = parseFiniteNumber( location.destinationLongitude || location.destinationLng || location.destinationLon || location.arrivalLongitude || location.arrivalLng || location.arrivalLon ); if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null; return normalizeDisplayRoutePoint({ latitude, longitude }); } function getDestinationName(location) { return firstString(location.destination, location.arrival); } function normalizeDisplayRoutePath(value) { if (!Array.isArray(value)) return []; return value.map(normalizeDisplayRoutePoint).filter(Boolean); } function normalizeDisplayRoutePoint(value) { if (!value) return null; const latitude = Array.isArray(value) ? parseFiniteNumber(value[0]) : parseFiniteNumber(value.latitude ?? value.lat); const longitude = Array.isArray(value) ? parseFiniteNumber(value[1]) : parseFiniteNumber(value.longitude ?? value.lng ?? value.lon); if (!Number.isFinite(latitude) || latitude < -90 || latitude > 90) return null; if (!Number.isFinite(longitude) || longitude < -180 || longitude > 180) return null; return { latitude, longitude }; } function createFallbackRoutePath(from, to, seed) { const deltaLatitude = to.latitude - from.latitude; const deltaLongitude = to.longitude - from.longitude; const length = Math.sqrt(deltaLatitude ** 2 + deltaLongitude ** 2) || 1; const offsetDirection = hashText(seed) % 2 === 0 ? 1 : -1; const offsetSize = Math.min(0.28, Math.max(0.02, length * 0.12)); const perpendicularLatitude = (-deltaLongitude / length) * offsetSize * offsetDirection; const perpendicularLongitude = (deltaLatitude / length) * offsetSize * offsetDirection; return [ from, { latitude: interpolateNumber(from.latitude, to.latitude, 0.36) + perpendicularLatitude, longitude: interpolateNumber(from.longitude, to.longitude, 0.36) + perpendicularLongitude }, { latitude: interpolateNumber(from.latitude, to.latitude, 0.72) - perpendicularLatitude * 0.35, longitude: interpolateNumber(from.longitude, to.longitude, 0.72) - perpendicularLongitude * 0.35 }, to ]; } function calculatePathDistanceKm(routePath) { let distance = 0; for (let index = 1; index < routePath.length; index += 1) { distance += calculateDistanceKm(routePath[index - 1], routePath[index]); } return distance; } function calculateDistanceKm(from, to) { const earthRadiusKm = 6371; const deltaLatitude = toRadians(to.latitude - from.latitude); const deltaLongitude = toRadians(to.longitude - from.longitude); const fromLatitude = toRadians(from.latitude); const toLatitude = toRadians(to.latitude); const a = Math.sin(deltaLatitude / 2) ** 2 + Math.cos(fromLatitude) * Math.cos(toLatitude) * Math.sin(deltaLongitude / 2) ** 2; return earthRadiusKm * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); } function interpolateNumber(from, to, progress) { return from + (to - from) * progress; } function toRadians(value) { return value * Math.PI / 180; } function hashText(value) { let hash = 0; for (const character of String(value)) { hash = (hash * 31 + character.charCodeAt(0)) >>> 0; } return hash; } function parseFiniteNumber(value) { if (value === undefined || value === null || value === "") return null; const parsed = Number(value); return Number.isFinite(parsed) ? parsed : null; } function parseOptionalDate(value) { if (!value) return null; const date = new Date(value); return Number.isNaN(date.getTime()) ? null : date; } function formatDistance(value) { const distance = Number(value); if (!Number.isFinite(distance)) return "-"; if (distance < 1) return `${Math.round(distance * 1000)} m`; if (distance < 10) return `${distance.toFixed(1)} km`; return `${Math.round(distance)} km`; } function formatDuration(minutes) { const duration = Math.max(0, Math.round(Number(minutes) || 0)); if (duration < 60) return `약 ${duration}분`; const hours = Math.floor(duration / 60); const remainingMinutes = duration % 60; return remainingMinutes ? `약 ${hours}시간 ${remainingMinutes}분` : `약 ${hours}시간`; } function formatEtaTime(value) { const date = value instanceof Date ? value : new Date(value); if (Number.isNaN(date.getTime())) return "-"; return new Intl.DateTimeFormat("ko-KR", { hour: "2-digit", minute: "2-digit" }).format(date); } function firstString(...values) { for (const value of values) { if (value === undefined || value === null) continue; const text = String(value).trim(); if (text) return text; } return ""; } function escapeHtml(value) { return String(value) .replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">") .replaceAll('"', """) .replaceAll("'", "'"); }