// チェーン着脱場・駐車帯マップ (function ($) { "use strict"; var route = "all"; var map; var defaultExtent; var locateBtn; var kp8_100 = []; var kp18_100 = []; var latlngs08 = []; var latlngs18 = []; var chainData = { points: [], trouble: [] }; var routeLayer08 = null; var routeLayer18 = null; var expresswayLayer = null; var niigataBorderLayer = null; var expresswayIcMarkers = []; var troubleLayers = []; var pointMarkers = []; var sapaMarkers = []; var routeMarkers = []; var userLocationMarker = null; var userLocationCircle = null; var dataReady = false; var activeAreaKey = null; // 地点データを更新したら上げる(ブラウザキャッシュ対策) var dataVersion = "20261021b"; var isYukiMobileView = window.matchMedia("(max-width: 767.98px)").matches || /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); if (isYukiMobileView) { if (history.scrollRestoration) { history.scrollRestoration = "manual"; } function scrollYukiPageTitleToTop() { var title = document.getElementById("yuki-page-title") || document.querySelector(".page-header h2.river"); if (title && title.scrollIntoView) { title.scrollIntoView({ block: "start", behavior: "auto" }); } else { window.scrollTo(0, 0); } } if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", scrollYukiPageTitleToTop); } else { scrollYukiPageTitleToTop(); } window.addEventListener("load", scrollYukiPageTitleToTop); setTimeout(scrollYukiPageTitleToTop, 50); } if (location.hostname === "dk-press.net" || location.hostname === "www.hrr.mlit.go.jp") { var wp_style_uri = "/takada/wp-content/themes/takada202012"; var wp_home_url = "/takada/"; } else { var wp_style_uri = tmp_path.style_uri; var wp_home_url = tmp_path.home_url; } var FACILITIES = [ { key: "phone", icon: "fac_phone.svg", label: "公衆電話" }, { key: "toilet", icon: "fac_toilet.svg", label: "公衆トイレ" }, { key: "light", icon: "fac_light.svg", label: "照明灯" } ]; // ポップアップ用の周辺拡大図。地理院タイルを必要な枚数だけ並べて切り抜く。 var MINI_ZOOM = 17; var TILE_SIZE = 256; var SAPA_LABEL_MIN_ZOOM = 11; var IC_LABEL_MIN_ZOOM = 11; // 国道8号・18号をまとめた初期表示(両路線が画面に収まる位置) var MAP_VIEW_ALL = [37.08, 138.15]; var MAP_ZOOM_ALL = 10; // エリア選択ボタンの表示位置とズーム var AREA_VIEWS = { r8j: { center: [37.22, 138.32], zoom: 12 }, r8n: { center: [37.11, 138.01], zoom: 12 }, r8i: { center: [37.0095, 137.742], zoom: 12 }, r18j: { center: [37.12, 138.24], zoom: 12 }, r18m: { center: [36.93, 138.22], zoom: 12 } }; function getMiniSize() { var el = document.getElementById("map"); var availW = el && el.clientWidth ? el.clientWidth : Math.min(window.innerWidth, 400); var availH = el && el.clientHeight ? el.clientHeight : Math.min(window.innerHeight, 500); var isNarrow = window.matchMedia("(max-width: 640px)").matches; if (isNarrow) { // タイトル・設備・余白・閉じるボタン分を除き、地図枠内に収める var byW = availW - 44; var byH = availH - 150; return Math.max(140, Math.min(220, byW, byH)); } return Math.min(480, Math.max(220, availW - 80)); } function getPopupMaxWidth() { var el = document.getElementById("map"); var mapW = el && el.clientWidth ? el.clientWidth : window.innerWidth; var isNarrow = window.matchMedia("(max-width: 640px)").matches; if (isNarrow) { return Math.max(180, Math.min(mapW - 16, window.innerWidth - 20, getMiniSize() + 28)); } return getMiniSize() + 40; } // 指定の中心・ズームで画面全体に見える地理範囲(fitBounds 一発用) function boundsForCenterZoom(center, zoom) { var c = L.latLng(center); var pw = map.project(c, zoom); var size = map.getSize(); var sw = map.unproject(L.point(pw.x - size.x / 2, pw.y + size.y / 2), zoom); var ne = map.unproject(L.point(pw.x + size.x / 2, pw.y - size.y / 2), zoom); return L.latLngBounds(sw, ne); } function setActiveArea(key) { activeAreaKey = key || null; var buttons = document.querySelectorAll(".chain-area-btn[data-area], .chain-area-btn[data-route]"); for (var i = 0; i < buttons.length; i++) { var btn = buttons[i]; var area = btn.getAttribute("data-area"); var route = btn.getAttribute("data-route"); var on = false; if (activeAreaKey && area) { on = area === activeAreaKey; } else if (activeAreaKey && route) { on = ("r" + route) === activeAreaKey; } if (on) { btn.classList.add("is-active"); btn.setAttribute("aria-pressed", "true"); } else { btn.classList.remove("is-active"); btn.setAttribute("aria-pressed", "false"); } } } function routeLayerBounds(route) { var layer = String(route) === "8" ? routeLayer08 : routeLayer18; if (layer && typeof layer.getBounds === "function") { var lb = layer.getBounds(); if (lb && lb.isValid()) { return lb; } } var latlngs = String(route) === "8" ? latlngs08 : latlngs18; if (!latlngs || !latlngs.length) { return null; } return L.latLngBounds(latlngs); } function goToRouteView(route, options) { if (!map) { return; } options = options || {}; var bounds = routeLayerBounds(route); if (!bounds || !bounds.isValid()) { return; } var isMobile = window.matchMedia("(max-width: 640px)").matches; var isRoute8 = String(route) === "8"; map.closePopup(); resetTroubleTooltips(); setActiveArea("r" + route); map.invalidateSize(); // 国道8号は東西に長いため、余白を確保して全体が収まるズームにする var padY = isMobile ? 24 : 36; var padRight = isMobile ? 24 : 40; var padLeft = Math.ceil(leftControlsWidth()) + (isMobile ? 16 : 24); var maxZoom; if (options.maxZoom != null) { maxZoom = options.maxZoom; } else if (isRoute8) { maxZoom = isMobile ? 9 : 10; } else { maxZoom = isMobile ? 10 : 11; } map.fitBounds(bounds, { paddingTopLeft: [padLeft, padY], paddingBottomRight: [padRight, padY + (isMobile ? 12 : 20)], maxZoom: maxZoom, animate: options.animate !== false }); } // エリア選択:左コントロール列を除いた範囲へ一発フィット function goToAreaView(view, options) { if (!map || !view) { return; } options = options || {}; map.closePopup(); resetTroubleTooltips(); map.invalidateSize(); var bounds = boundsForCenterZoom(view.center, view.zoom); fitBoundsAvoidingLeftControls(bounds, { maxZoom: view.zoom, animate: options.animate !== false }); } function leftControlsWidth() { var leftStack = document.querySelector("#map .leaflet-top.leaflet-left"); if (!leftStack) { return 0; } var box = leftStack.getBoundingClientRect(); return box.width > 0 ? box.width : 0; } function setViewAvoidingLeftControls(center, zoom, options) { if (!map) { return; } options = options || {}; var animate = options.animate !== false; var latlng = L.latLng(center); var z = zoom; var padLeft = leftControlsWidth(); if (padLeft > 0) { var p = map.project(latlng, z); p.x -= padLeft / 2; latlng = map.unproject(p, z); } map.setView(latlng, z, { animate: animate }); } function fitBoundsAvoidingLeftControls(bounds, options) { if (!map || !bounds || !bounds.isValid()) { return; } options = options || {}; map.invalidateSize(); var padLeft = Math.ceil(leftControlsWidth()) + 16; map.fitBounds(bounds, { paddingTopLeft: [padLeft, 28], paddingBottomRight: [56, 52], maxZoom: options.maxZoom != null ? options.maxZoom : 12, animate: options.animate !== false }); } // ホーム用:国道8号・18号のみ(高速道路は含めない) function nationalRouteBounds() { var bounds = null; function extendLayer(layer) { if (!layer || typeof layer.getBounds !== "function") { return; } var b = layer.getBounds(); if (!b || !b.isValid()) { return; } bounds = bounds ? bounds.extend(b) : L.latLngBounds(b.getSouthWest(), b.getNorthEast()); } extendLayer(routeLayer08); extendLayer(routeLayer18); return bounds; } function fitAllRoutes(options) { if (!map) { return; } options = options || {}; var animate = options.animate !== false; var isMobile = window.matchMedia("(max-width: 640px)").matches; map.closePopup(); resetTroubleTooltips(); setActiveArea(null); // PC・スマホとも国道8号・18号のみ(高速道路は含めない) var bounds = nationalRouteBounds(); if (!bounds || !bounds.isValid()) { map.setView(MAP_VIEW_ALL, MAP_ZOOM_ALL, { animate: animate }); return; } map.invalidateSize(); map.fitBounds(bounds, { padding: isMobile ? [18, 18] : [28, 28], maxZoom: isMobile ? 10 : 11, animate: animate }); } function miniTilesHtml(layer, ext, className, left, top, size) { var tiles = []; for (var ty = Math.floor(top / TILE_SIZE); ty <= Math.floor((top + size - 1) / TILE_SIZE); ty++) { for (var tx = Math.floor(left / TILE_SIZE); tx <= Math.floor((left + size - 1) / TILE_SIZE); tx++) { tiles.push( '' ); } } return tiles.join(""); } function miniMapHtml(lat, lng) { var size = getMiniSize(); var world = Math.pow(2, MINI_ZOOM) * TILE_SIZE; var rad = lat * Math.PI / 180; var centerX = (lng + 180) / 360 * world; var centerY = (1 - Math.log(Math.tan(rad) + 1 / Math.cos(rad)) / Math.PI) / 2 * world; var left = centerX - size / 2; var top = centerY - size / 2; return '
' + miniTilesHtml("seamlessphoto", "jpg", "chain-minimap-tile", left, top, size) + '' + '地理院タイル(航空写真)' + "
"; } function facilityHtml(point) { var badges = []; for (var i = 0; i < FACILITIES.length; i++) { var fac = FACILITIES[i]; if (!point[fac.key]) { continue; } badges.push( '' + '' + "" + fac.label + "" + "" ); } var facilities = badges.length ? '
' + badges.join("") + "
" : '
設備の登録はありません
'; var note = point.note ? '
' + point.note + "
" : ""; return '
' + '
' + point.name + "
" + miniMapHtml(point.lat, point.lng) + facilities + note + '
国道' + point.route + "号 / KP " + parseFloat(point.kp).toFixed(1) + "
" + "
"; } function getPopupOptions() { var isNarrow = window.matchMedia("(max-width: 640px)").matches; var padLeft = isNarrow ? 8 : 56; var padTop = isNarrow ? 8 : 20; var padRight = isNarrow ? 8 : 56; var padBottom = isNarrow ? 8 : 64; if (!isNarrow) { var leftStack = document.querySelector("#map .leaflet-top.leaflet-left"); if (leftStack) { var box = leftStack.getBoundingClientRect(); if (box.width > 0) { padLeft = Math.ceil(box.width) + 16; } } } return { maxWidth: getPopupMaxWidth(), minWidth: 0, className: "chain-leaflet-popup", // 左矢印(約8px)分だけ右へずらして先端をマーカーへ寄せる offset: L.point(10, 0), autoPan: false, keepInView: false, autoPanPaddingTopLeft: L.point(padLeft, padTop), autoPanPaddingBottomRight: L.point(padRight, padBottom) }; } // Leaflet既定は上開き(tipは下中央)。 // CSSで tip を左中央に移すので、位置計算も右開きに合わせる function enablePopupOpenRight(popup) { if (!popup || popup._chainOpenRight) { return; } popup._chainOpenRight = true; popup._updatePosition = function () { if (!this._map || !this._container) { return; } var pos = this._map.latLngToLayerPoint(this._latlng); var offset = L.point(this.options.offset || [0, 0]); var anchor = L.point(0, 0); if (this._source && typeof this._source._getPopupAnchor === "function") { anchor = L.point(this._source._getPopupAnchor()); } // transform 原点をマーカー(+popupAnchor)に置く L.DomUtil.setPosition(this._container, pos.add(anchor)); var height = this._container.offsetHeight; this._containerWidth = this._container.offsetWidth; // tipは左側・縦中央。左端をマーカー近くに置き、縦は中央揃え // Leaflet: topY = pos.y - height - containerBottom this._containerLeft = offset.x; this._containerBottom = -Math.round(height / 2); this._container.style.left = this._containerLeft + "px"; this._container.style.bottom = this._containerBottom + "px"; }; } // 実描画後の矩形でマップ内に収まるようパン(1回にまとめてカクつき防止) function ensurePopupInMap(popup, options) { if (!popup || !popup._map || !popup._container) { return; } if (typeof popup.isOpen === "function" && !popup.isOpen()) { return; } options = options || {}; if (typeof popup._updateLayout === "function") { popup._updateLayout(); } if (typeof popup._updatePosition === "function") { popup._updatePosition(); } var mapInstance = popup._map; var mapRect = mapInstance.getContainer().getBoundingClientRect(); var popRect = popup._container.getBoundingClientRect(); if (!mapRect.width || !popRect.width) { return; } var padTL = L.point(popup.options.autoPanPaddingTopLeft || [8, 8]); var padBR = L.point(popup.options.autoPanPaddingBottomRight || [8, 8]); var dx = 0; var dy = 0; if (popRect.right + padBR.x > mapRect.right) { dx = popRect.right + padBR.x - mapRect.right; } if (popRect.left - dx < mapRect.left + padTL.x) { dx = popRect.left - (mapRect.left + padTL.x); } if (popRect.bottom + padBR.y > mapRect.bottom) { dy = popRect.bottom + padBR.y - mapRect.bottom; } if (popRect.top - dy < mapRect.top + padTL.y) { dy = popRect.top - (mapRect.top + padTL.y); } if (dx || dy) { mapInstance.panBy([dx, dy], { animate: options.animate !== false }); } } function schedulePopupInMap(popup) { if (!popup) { return; } // 同一オープン中の多重パンを避ける if (popup._chainPanTimer) { clearTimeout(popup._chainPanTimer); popup._chainPanTimer = null; } if (popup._chainPanRaf) { if (typeof window.cancelAnimationFrame === "function") { window.cancelAnimationFrame(popup._chainPanRaf); } popup._chainPanRaf = null; } function runOnce() { popup._chainPanRaf = null; popup._chainPanTimer = null; ensurePopupInMap(popup, { animate: true }); } // レイアウト確定後に1回だけスムーズパン if (typeof window.requestAnimationFrame === "function") { popup._chainPanRaf = window.requestAnimationFrame(function () { popup._chainPanRaf = window.requestAnimationFrame(runOnce); }); } else { popup._chainPanTimer = setTimeout(runOnce, 32); } } function schedulePopupInMapAfterImages(popup) { if (!popup || !popup._container) { return; } var imgs = popup._container.querySelectorAll("img"); var pending = 0; function onDone() { pending -= 1; if (pending > 0) { return; } // 画像読込完了後も1回だけ(短くデバウンス) if (popup._chainImgPanTimer) { clearTimeout(popup._chainImgPanTimer); } popup._chainImgPanTimer = setTimeout(function () { popup._chainImgPanTimer = null; ensurePopupInMap(popup, { animate: true }); }, 80); } for (var i = 0; i < imgs.length; i++) { if (imgs[i].complete) { continue; } pending += 1; imgs[i].addEventListener("load", onDone); imgs[i].addEventListener("error", onDone); } } function kpBetween(kp, from, to) { var min = Math.min(from, to); var max = Math.max(from, to); return kp >= min && kp <= max; } function polylineByKp(kpList, from, to) { var coords = []; for (var i = 0; i < kpList.length; i++) { var kp = parseFloat(kpList[i].kp); if (kpBetween(kp, from, to)) { coords.push([parseFloat(kpList[i].lat), parseFloat(kpList[i].lng)]); } } return coords; } function nearestKpIndex(kpList, lat, lng) { var best = 0; var bestDist = Infinity; for (var i = 0; i < kpList.length; i++) { var dLat = parseFloat(kpList[i].lat) - lat; var dLng = (parseFloat(kpList[i].lng) - lng) * 0.8; var dist = dLat * dLat + dLng * dLng; if (dist < bestDist) { bestDist = dist; best = i; } } return best; } function iconBox(latlng, icon, pad) { var size = icon.options.iconSize; var anchor = icon.options.iconAnchor || [size[0] / 2, size[1] / 2]; var pt = map.latLngToLayerPoint(latlng); return { left: pt.x - anchor[0] - pad, top: pt.y - anchor[1] - pad, right: pt.x - anchor[0] + size[0] + pad, bottom: pt.y - anchor[1] + size[1] + pad }; } function boxesOverlap(a, b) { return a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom; } function hitsAny(latlng, icon, boxes) { var box = iconBox(latlng, icon, 0); for (var i = 0; i < boxes.length; i++) { if (boxesOverlap(box, boxes[i])) { return true; } } return false; } var ROUTE_SHIFT_STRIDE = 3; var ROUTE_SHIFT_MAX = 200; var MARKER_GAP = 3; var ROUTE_ICON_BASE = 36; var ROUTE_ICON_SCALES = [1, 0.85, 0.7, 0.6, 0.5]; function routeIconAtScale(isR8, scale) { var size = Math.max(1, Math.round(ROUTE_ICON_BASE * scale)); var url = wp_style_uri + "/sekisetu/icon/" + (isR8 ? "R8.svg" : "R18.svg"); return L.icon({ iconUrl: url, iconRetinaUrl: url, iconSize: [size, size], iconAnchor: [size / 2, Math.round(size * 2 / 3)], className: "leaflet-terminator" }); } function relocateRouteMarkers() { if (!map || !routeMarkers.length) { return; } var obstacles = []; var i; for (i = 0; i < pointMarkers.length; i++) { obstacles.push(iconBox(pointMarkers[i].getLatLng(), pointMarkers[i].options.icon, MARKER_GAP)); } for (i = 0; i < sapaMarkers.length; i++) { obstacles.push(iconBox(sapaMarkers[i].getLatLng(), sapaMarkers[i].options.icon, MARKER_GAP)); } for (i = 0; i < routeMarkers.length; i++) { var marker = routeMarkers[i]; var isR8 = marker.homeRoute === "8"; var kpList = isR8 ? kp8_100 : kp18_100; var placed = null; var placedScale = ROUTE_ICON_SCALES[ROUTE_ICON_SCALES.length - 1]; var placedIcon = null; for (var si = 0; si < ROUTE_ICON_SCALES.length && !placed; si++) { var scale = ROUTE_ICON_SCALES[si]; var icon = routeIconAtScale(isR8, scale); for (var step = 0; step <= ROUTE_SHIFT_MAX && !placed; step += ROUTE_SHIFT_STRIDE) { var offsets = step === 0 ? [0] : [step, -step]; for (var d = 0; d < offsets.length; d++) { var idx = marker.homeIndex + offsets[d]; if (idx < 0 || idx >= kpList.length) { continue; } var candidate = L.latLng(parseFloat(kpList[idx].lat), parseFloat(kpList[idx].lng)); if (!hitsAny(candidate, icon, obstacles)) { placed = candidate; placedScale = scale; placedIcon = icon; break; } } } } if (!placed) { placed = marker.homeLatLng; placedScale = ROUTE_ICON_SCALES[ROUTE_ICON_SCALES.length - 1]; placedIcon = routeIconAtScale(isR8, placedScale); } marker.setIcon(placedIcon); marker.setLatLng(placed); marker._routeIconScale = placedScale; obstacles.push(iconBox(placed, placedIcon, MARKER_GAP)); } } function clearDynamicLayers() { for (var i = 0; i < troubleLayers.length; i++) { map.removeLayer(troubleLayers[i]); } troubleLayers = []; for (var j = 0; j < pointMarkers.length; j++) { map.removeLayer(pointMarkers[j]); } pointMarkers = []; } function expresswayIcIcon(name, showLabel, labelSide) { var html = ''; if (showLabel) { var sideClass = ""; if (labelSide === "left") { sideClass = " is-left"; } else if (labelSide === "bottom") { sideClass = " is-bottom"; } else if (labelSide === "top") { sideClass = " is-top"; } html += '' + name + ""; } return L.divIcon({ className: "expressway-ic-marker leaflet-terminator" + (showLabel ? "" : " labels-hidden"), html: html, iconSize: [14, 14], iconAnchor: [7, 7] }); } function updateDensityLayers() { if (!map) { return; } var z = map.getZoom(); var showIcLabel = z >= IC_LABEL_MIN_ZOOM; var showSapaLabel = z >= SAPA_LABEL_MIN_ZOOM; var i; for (i = 0; i < expresswayIcMarkers.length; i++) { var ic = expresswayIcMarkers[i]; if (ic._showLabel === showIcLabel) { continue; } ic._showLabel = showIcLabel; ic.setIcon(expresswayIcIcon(ic._icName, showIcLabel, ic._labelSide)); } for (i = 0; i < sapaMarkers.length; i++) { var sm = sapaMarkers[i]; if (sm._sapaLabelOn === showSapaLabel) { continue; } sm._sapaLabelOn = showSapaLabel; sm.unbindTooltip(); sm.bindTooltip(sm._sapaTipHtml, { direction: sm._sapaTipDir, permanent: showSapaLabel, offset: sm._sapaTipOffset, opacity: 1.0, className: "chain-sapa-tooltip" }); } } function openPointByIndex(index) { if (!pointMarkers[index]) { return; } var marker = pointMarkers[index]; map.closePopup(); resetTroubleTooltips(); map.setView(marker.getLatLng(), Math.max(map.getZoom(), 13), { animate: true }); setTimeout(function () { marker.openPopup(); }, 320); } function troubleTooltipAnchor(layer) { if (!layer) { return null; } // 線分上の中点(bounds中心だと海岸線で海側にずれる) if (typeof layer.getCenter === "function" && layer._map) { try { return layer.getCenter(); } catch (err) { // fall through } } if (typeof layer.getBounds === "function") { var b = layer.getBounds(); if (b && b.isValid()) { return b.getCenter(); } } return null; } function findTroubleLayerByIndex(index) { var sec = chainData.trouble && chainData.trouble[index]; if (!sec) { return troubleLayers[index] || null; } for (var i = 0; i < troubleLayers.length; i++) { var layer = troubleLayers[i]; if (!layer || !layer._chainTrouble) { continue; } if (layer._chainTrouble === sec || layer._chainTrouble.name === sec.name) { return layer; } } return troubleLayers[index] || null; } // 区間全体が見えるようフィット(国道8号は北側=海側に余白を多め) function fitTroubleSection(layer, options) { if (!map || !layer || typeof layer.getBounds !== "function") { return; } options = options || {}; var bounds = layer.getBounds(); if (!bounds || !bounds.isValid()) { return; } var route = layer._chainTrouble ? String(layer._chainTrouble.route) : ""; var isMobile = window.matchMedia("(max-width: 640px)").matches; var padLeft = Math.ceil(leftControlsWidth()) + (isMobile ? 12 : 16); var padTop = isMobile ? 28 : 36; var padRight = isMobile ? 28 : 48; var padBottom = isMobile ? 36 : 52; if (route === "8") { // 海岸線が北側のため、上余白を増やして道路を画面中央寄りに padTop = isMobile ? 72 : 100; padBottom = isMobile ? 20 : 28; } map.invalidateSize(); map.fitBounds(bounds, { paddingTopLeft: [padLeft, padTop], paddingBottomRight: [padRight, padBottom], maxZoom: options.maxZoom != null ? options.maxZoom : 13, animate: options.animate !== false }); } function openTroubleByIndex(index) { var layer = findTroubleLayerByIndex(index); if (!map || !layer) { return; } map.closePopup(); resetTroubleTooltips(); fitTroubleSection(layer, { maxZoom: 13, animate: true }); if (typeof layer.openTooltip === "function") { setTimeout(function () { var anchor = troubleTooltipAnchor(layer); layer.openTooltip(anchor || undefined); }, 300); } } function getTroubleTooltipBindOptions(layer, permanent) { var route = layer && layer._chainTrouble ? String(layer._chainTrouble.route) : ""; return { sticky: !permanent, permanent: !!permanent, // 国道8号は海岸沿いのため、吹き出しを線の上側に出す direction: route === "8" ? "top" : "auto", opacity: 0.95, className: "chain-trouble-tooltip" }; } function rebindTroubleTooltip(layer, permanent) { if (!layer) { return; } var content = ""; if (layer._chainTrouble) { content = troubleTooltipHtml(layer._chainTrouble.name); } else if (typeof layer.getTooltip === "function" && layer.getTooltip()) { content = layer.getTooltip().getContent(); } if (!content) { return; } if (typeof layer.unbindTooltip === "function") { layer.unbindTooltip(); } layer.bindTooltip(content, getTroubleTooltipBindOptions(layer, permanent)); if (permanent && typeof layer.openTooltip === "function") { var anchor = troubleTooltipAnchor(layer); layer.openTooltip(anchor || undefined); } } function resetTroubleTooltips() { for (var i = 0; i < troubleLayers.length; i++) { rebindTroubleTooltip(troubleLayers[i], false); } } function openAllTroubleTooltips() { for (var i = 0; i < troubleLayers.length; i++) { rebindTroubleTooltip(troubleLayers[i], true); } } function showAllTroubleSections() { if (!map || !troubleLayers.length) { return; } map.closePopup(); var bounds = null; for (var i = 0; i < troubleLayers.length; i++) { var layer = troubleLayers[i]; if (!layer || typeof layer.getBounds !== "function") { continue; } var b = layer.getBounds(); if (!b || !b.isValid()) { continue; } bounds = bounds ? bounds.extend(b) : L.latLngBounds(b); } if (!bounds || !bounds.isValid()) { return; } map.fitBounds(bounds, { padding: [40, 40], maxZoom: 12, animate: true }); setTimeout(function () { openAllTroubleTooltips(); }, 320); } function troubleSectionLabel(name) { if (!name) { return ""; } var m = String(name).match(/((.+))/); return m ? m[1] : name; } function troubleTooltipHtml(name) { var section = troubleSectionLabel(name); return '
' + '
登坂不能車多発区間
' + '
' + section + "
" + "
"; } function renderPointList() { var body = document.getElementById("chain-point-list-body"); if (!body || !chainData.points) { return; } function facilityIconsHtml(point) { var icons = []; for (var f = 0; f < FACILITIES.length; f++) { var fac = FACILITIES[f]; if (point[fac.key]) { icons.push( '' + '' + fac.label + '' + "" ); } else { icons.push(''); } } return '' + icons.join("") + ""; } var col8 = []; var col18 = []; for (var i = 0; i < chainData.points.length; i++) { var p = chainData.points[i]; var item = '"; if (String(p.route) === "8") { col8.push(item); } else { col18.push(item); } } // 国道8号は北寄り(米山海岸)から表示 col8.reverse(); body.innerHTML = '
' + '

国道8号

' + '

至新潟方面

' + '
' + (col8.join("") || '

該当なし

') + "
" + '

至富山方面

' + "
" + '
' + '

国道18号

' + '

至上越方面

' + '
' + (col18.join("") || '

該当なし

') + "
" + '

至長野方面

' + "
"; $(body).off("click.chainlist").on("click.chainlist", ".chain-point-item", function () { var idx = parseInt(this.getAttribute("data-index"), 10); closeListModal(function () { openPointByIndex(idx); var mapEl = document.getElementById("map"); if (mapEl && mapEl.scrollIntoView) { mapEl.scrollIntoView({ behavior: "smooth", block: "center" }); } }); }); } function renderTroubleList() { var body = document.getElementById("chain-trouble-list-body"); if (!body || !chainData.trouble) { return; } var col8 = []; var col18 = []; for (var i = 0; i < chainData.trouble.length; i++) { var sec = chainData.trouble[i]; var label = troubleSectionLabel(sec.name); var item = '"; if (String(sec.route) === "8") { col8.push(item); } else { col18.push(item); } } // 国道8号は新潟方面(雁子浜側)から表示 col8.reverse(); body.innerHTML = '
' + '

国道8号

' + '

至新潟方面

' + '
' + (col8.join("") || '

該当なし

') + "
" + '

至富山方面

' + "
" + '
' + '

国道18号

' + '

至上越方面

' + '
' + (col18.join("") || '

該当なし

') + "
" + '

至長野方面

' + "
"; $(body).off("click.chaintrouble").on("click.chaintrouble", ".chain-trouble-item", function () { var idx = parseInt(this.getAttribute("data-index"), 10); closeListModal(function () { openTroubleByIndex(idx); var mapEl = document.getElementById("map"); if (mapEl && mapEl.scrollIntoView) { mapEl.scrollIntoView({ behavior: "smooth", block: "center" }); } }); }); } function bindTroubleShowAll() { $(document).off("click.chaintroubleall", "#chain-trouble-show-all").on("click.chaintroubleall", "#chain-trouble-show-all", function () { closeListModal(function () { showAllTroubleSections(); var mapEl = document.getElementById("map"); if (mapEl && mapEl.scrollIntoView) { mapEl.scrollIntoView({ behavior: "smooth", block: "center" }); } }); }); } function renderRouteContent() { if (!map || !dataReady) { return; } clearDynamicLayers(); for (var t = 0; t < chainData.trouble.length; t++) { var sec = chainData.trouble[t]; var kpList = String(sec.route) === "8" ? kp8_100 : kp18_100; var line = polylineByKp(kpList, sec.kp_from, sec.kp_to); if (line.length > 1) { var layer = L.polyline(line, { color: "#E50000", weight: 8, opacity: 0.85, className: "leaflet-terminator" }).addTo(map); layer._chainTrouble = sec; layer.bindTooltip(troubleTooltipHtml(sec.name), getTroubleTooltipBindOptions(layer, false)); troubleLayers.push(layer); } } for (var p = 0; p < chainData.points.length; p++) { var point = chainData.points[p]; var marker = L.marker([point.lat, point.lng], { icon: chainIcon, title: point.name, riseOnHover: true, zIndexOffset: 200 }).addTo(map); marker._chainPoint = point; (function (markerRef) { markerRef.bindPopup(function () { return facilityHtml(markerRef._chainPoint); }, getPopupOptions()); })(marker); enablePopupOpenRight(marker.getPopup()); marker.bindTooltip("" + point.name + "", { direction: "top", offset: [0, -8], opacity: 1.0 }); pointMarkers.push(marker); } relocateRouteMarkers(); renderPointList(); renderTroubleList(); updateDensityLayers(); } function bindAreaBar() { var bar = document.getElementById("chain-area-bar"); if (!bar) { return; } $(bar).off("click.chainarea").on("click.chainarea", ".chain-area-btn[data-area]", function () { var key = this.getAttribute("data-area"); var view = AREA_VIEWS[key]; if (!view) { return; } setActiveArea(key); goToAreaView(view); }); $(bar).off("click.chainroute").on("click.chainroute", ".chain-area-btn[data-route]", function () { goToRouteView(this.getAttribute("data-route")); }); $(bar).off("click.chainhome").on("click.chainhome", "#chain-home-btn, .chain-home-btn", function () { fitAllRoutes(); }); setActiveArea(null); } function getListModal() { var el = document.getElementById("chain-list-modal"); if (!el) { return null; } if (typeof UIkit !== "undefined" && UIkit.modal) { return UIkit.modal(el); } return null; } function openListModal() { var modal = getListModal(); if (modal) { modal.show(); return; } var el = document.getElementById("chain-list-modal"); if (el) { el.classList.add("uk-open"); el.style.display = "block"; } } function closeListModal(done) { var modal = getListModal(); var finished = false; function finish() { if (finished) { return; } finished = true; if (typeof done === "function") { done(); } } if (modal) { var el = document.getElementById("chain-list-modal"); if (el) { $(el).one("hidden", finish); } modal.hide(); setTimeout(finish, 320); return; } var fallback = document.getElementById("chain-list-modal"); if (fallback) { fallback.classList.remove("uk-open"); fallback.style.display = "none"; } finish(); } function setListModalTab(tabKey) { var key = tabKey === "trouble" ? "trouble" : "point"; var tabs = document.querySelectorAll(".chain-list-tab"); var panels = { point: document.getElementById("chain-point-list"), trouble: document.getElementById("chain-trouble-list") }; for (var i = 0; i < tabs.length; i++) { var tab = tabs[i]; var isActive = tab.getAttribute("data-list-tab") === key; tab.classList.toggle("is-active", isActive); tab.setAttribute("aria-selected", isActive ? "true" : "false"); tab.tabIndex = isActive ? 0 : -1; } if (panels.point) { panels.point.hidden = key !== "point"; panels.point.classList.toggle("is-active", key === "point"); } if (panels.trouble) { panels.trouble.hidden = key !== "trouble"; panels.trouble.classList.toggle("is-active", key === "trouble"); } } function bindListModal() { $(document).off("click.chainlistopen", "#chain-list-btn").on("click.chainlistopen", "#chain-list-btn", function (e) { // uk-toggle がある場合は UIkit に任せるが、未読込時はフォールバック if (typeof UIkit === "undefined" || !UIkit.modal) { e.preventDefault(); openListModal(); } }); $(document).off("click.chainlisttab", ".chain-list-tab").on("click.chainlisttab", ".chain-list-tab", function () { setListModalTab(this.getAttribute("data-list-tab")); }); } new Vue({ el: "#app", mounted: function () { setTimeout(function () { if (map) { map.invalidateSize(); } }, 0); } }); map = L.map("map", { center: MAP_VIEW_ALL, zoom: MAP_ZOOM_ALL, minZoom: 8, maxZoom: 16, scrollWheelZoom: false }); map.on("popupopen", function (e) { var popup = e.popup; if (!popup) { return; } enablePopupOpenRight(popup); var opts = getPopupOptions(); popup.options.autoPanPaddingTopLeft = opts.autoPanPaddingTopLeft; popup.options.autoPanPaddingBottomRight = opts.autoPanPaddingBottomRight; popup.options.maxWidth = opts.maxWidth; popup.options.minWidth = 0; popup.options.offset = opts.offset; // Leaflet 標準 autoPan と自前パンの二重実行を避け、描画後に1回だけパン popup.options.autoPan = false; popup.options.keepInView = false; if (typeof popup._updateLayout === "function") { popup._updateLayout(); } if (typeof popup._updatePosition === "function") { popup._updatePosition(); } schedulePopupInMap(popup); schedulePopupInMapAfterImages(popup); }); map.on("popupclose", function (e) { var popup = e.popup; if (!popup) { return; } if (popup._chainPanTimer) { clearTimeout(popup._chainPanTimer); popup._chainPanTimer = null; } if (popup._chainImgPanTimer) { clearTimeout(popup._chainImgPanTimer); popup._chainImgPanTimer = null; } if (popup._chainPanRaf && typeof window.cancelAnimationFrame === "function") { window.cancelAnimationFrame(popup._chainPanRaf); popup._chainPanRaf = null; } }); defaultExtent = L.control.defaultExtent({ title: "初期表示に戻す" }); defaultExtent.setZoom(MAP_ZOOM_ALL); defaultExtent.setCenter(MAP_VIEW_ALL); // ホームは地図下のエリアバーへ移したため、地図上コントロールには追加しない defaultExtent._zoomToDefault = function () { fitAllRoutes(); }; locateBtn = L.easyButton({ id: "btn-locate", position: "bottomright", states: [{ stateName: "locate-off", icon: "fa-location-arrow", title: "現在地を表示", onClick: function (btn, mapInstance) { btn.button.style.opacity = "0.6"; var isMobile = window.matchMedia("(max-width: 640px)").matches; mapInstance.locate({ setView: true, maxZoom: isMobile ? 13 : 14, enableHighAccuracy: false, timeout: 15000, maximumAge: 0 }); } }] }); locateBtn.addTo(map); if (locateBtn.getContainer) { L.DomUtil.addClass(locateBtn.getContainer(), "locate-control"); } else if (locateBtn._container) { L.DomUtil.addClass(locateBtn._container, "locate-control"); } if (map.attributionControl) { map.attributionControl.setPosition("bottomleft"); } map.on("locationfound", function (e) { if (userLocationCircle) { map.removeLayer(userLocationCircle); } if (userLocationMarker) { map.removeLayer(userLocationMarker); } userLocationCircle = L.circle(e.latlng, { radius: Math.max(e.accuracy / 2, 30), color: "#1a73e8", fillColor: "#4285f4", fillOpacity: 0.15, weight: 1, interactive: false }).addTo(map); userLocationMarker = L.marker(e.latlng, { icon: L.divIcon({ className: "user-location-marker", html: '', iconSize: [40, 40], iconAnchor: [20, 20] }), zIndexOffset: 1000, title: "現在地" }).addTo(map).bindPopup("現在地"); if (locateBtn && locateBtn.button) { locateBtn.button.style.opacity = "1"; } }); map.on("zoomend", function () { relocateRouteMarkers(); updateDensityLayers(); }); map.on("locationerror", function () { if (locateBtn && locateBtn.button) { locateBtn.button.style.opacity = "1"; } alert("現在地を取得できませんでした。ブラウザの位置情報利用を許可してください。"); }); bindAreaBar(); bindListModal(); bindTroubleShowAll(); map.setView(MAP_VIEW_ALL, MAP_ZOOM_ALL, { animate: false }); L.tileLayer("https://cyberjapandata.gsi.go.jp/xyz/pale/{z}/{x}/{y}.png", { attribution: "地理院タイル" }).addTo(map); var chainIcon = L.icon({ iconUrl: wp_style_uri + "/sekisetu/icon/chain.svg", iconRetinaUrl: wp_style_uri + "/sekisetu/icon/chain.svg", iconSize: [38, 38], iconAnchor: [19, 19], popupAnchor: [0, 0], tooltipAnchor: [19, 0], className: "chain-marker" }); var sapaIcon08 = L.icon({ iconUrl: wp_style_uri + "/sekisetu/icon/sapa_icon.svg", iconRetinaUrl: wp_style_uri + "/sekisetu/icon/sapa_icon.svg", iconSize: [40, 40], iconAnchor: [18, 40], tooltipAnchor: [0, -40], className: "leaflet-terminator" }); var sapaIcon18 = L.icon({ iconUrl: wp_style_uri + "/sekisetu/icon/sapa_icon.svg", iconRetinaUrl: wp_style_uri + "/sekisetu/icon/sapa_icon.svg", iconSize: [40, 40], iconAnchor: [40, 24], tooltipAnchor: [0, 0], className: "leaflet-terminator" }); var routeIcon = []; routeIcon[0] = routeIconAtScale(true, 1); routeIcon[1] = routeIconAtScale(false, 1); $.when( $.getJSON({ url: wp_style_uri + "/sekisetu/kp/08_100.json?ver=" + dataVersion }), $.getJSON({ url: wp_style_uri + "/sekisetu/kp/18_100.json?ver=" + dataVersion }), $.getJSON({ url: wp_style_uri + "/sekisetu/chain.json?ver=" + dataVersion }), $.getJSON({ url: wp_style_uri + "/sekisetu/sapa.json?ver=" + dataVersion }), $.getJSON({ url: wp_style_uri + "/sekisetu/route.json?ver=" + dataVersion }), $.getJSON({ url: wp_style_uri + "/sekisetu/expressway.json?ver=" + dataVersion }), $.getJSON({ url: wp_style_uri + "/sekisetu/expressway-ic.json?ver=" + dataVersion }), $.getJSON({ url: wp_style_uri + "/sekisetu/niigata-border.json?ver=" + dataVersion }) ).done(function (kp8Res, kp18Res, chainRes, sapaRes, routeRes, expressRes, expressIcRes, borderRes) { try { kp8_100 = Array.isArray(kp8Res[0]) ? kp8Res[0] : kp8Res; kp18_100 = Array.isArray(kp18Res[0]) ? kp18Res[0] : kp18Res; chainData = (chainRes[0] && chainRes[0].points) ? chainRes[0] : chainRes; for (var i = 0; i < kp8_100.length; i++) { latlngs08[i] = [parseFloat(kp8_100[i].lat), parseFloat(kp8_100[i].lng)]; } for (var j = 0; j < kp18_100.length; j++) { latlngs18[j] = [parseFloat(kp18_100[j].lat), parseFloat(kp18_100[j].lng)]; } // 新潟県境(路線の下に敷く) var borderData = borderRes[0] && borderRes[0].features ? borderRes[0] : borderRes; niigataBorderLayer = L.geoJSON(borderData, { style: { color: "#7A3E9D", weight: 2.5, opacity: 0.95, fill: false, fillOpacity: 0, dashArray: "10 4 2 4", lineJoin: "round", className: "leaflet-terminator niigata-border-line" }, interactive: false }).addTo(map); if (niigataBorderLayer.bringToBack) { niigataBorderLayer.bringToBack(); } var expressData = expressRes[0] && expressRes[0].features ? expressRes[0] : expressRes; expresswayLayer = L.geoJSON(expressData, { style: { color: "#1B9E4B", weight: 5, opacity: 0.95, lineJoin: "round", lineCap: "round", className: "leaflet-terminator expressway-line" }, onEachFeature: function (feature, layer) { var p = feature.properties || {}; var label = p.name || p.ref || "高速道路"; if (p.ref && p.name && p.name.indexOf(p.ref) === -1) { label = p.name + "(" + p.ref + ")"; } layer.bindTooltip(label, { sticky: true, opacity: 0.9 }); } }).addTo(map); var showIcLabel = map.getZoom() >= IC_LABEL_MIN_ZOOM; var expressIcObj = Array.isArray(expressIcRes[0]) ? expressIcRes[0] : expressIcRes; for (var e = 0; e < expressIcObj.length; e++) { var ic = expressIcObj[e]; var icMarker = L.marker([parseFloat(ic.lat), parseFloat(ic.lng)], { icon: expresswayIcIcon(ic.name, showIcLabel, ic.labelSide), title: ic.name, zIndexOffset: -200, keyboard: false }).addTo(map); icMarker._icName = ic.name; icMarker._labelSide = ic.labelSide || "right"; icMarker._showLabel = showIcLabel; expresswayIcMarkers.push(icMarker); } routeLayer08 = L.polyline(latlngs08, { color: "#666666", weight: 6, className: "leaflet-terminator" }).addTo(map); routeLayer18 = L.polyline(latlngs18, { color: "#666666", weight: 6, className: "leaflet-terminator" }).addTo(map); var showSapaLabel = map.getZoom() >= SAPA_LABEL_MIN_ZOOM; var sapaObj = Array.isArray(sapaRes[0]) ? sapaRes[0] : sapaRes; for (var s = 0; s < sapaObj.length; s++) { var sapa = sapaObj[s]; var icon = String(sapa.route) === "18" ? sapaIcon18 : sapaIcon08; var m = L.marker([parseFloat(sapa.lat), parseFloat(sapa.lng)], { icon: icon, title: sapa.name, riseOnHover: true }).addTo(map); m._sapaTipHtml = '道の駅 ' + sapa.name + ""; m._sapaTipDir = String(sapa.route) === "18" ? "left" : "top"; m._sapaTipOffset = String(sapa.route) === "18" ? [-40, -5] : [0, 0]; m._sapaLabelOn = showSapaLabel; m.bindTooltip(m._sapaTipHtml, { direction: m._sapaTipDir, permanent: showSapaLabel, offset: m._sapaTipOffset, opacity: 1.0, className: "chain-sapa-tooltip" }); sapaMarkers.push(m); } var routeObj = Array.isArray(routeRes[0]) ? routeRes[0] : routeRes; for (var r = 0; r < routeObj.length; r++) { var isR8 = String(routeObj[r].route) === "8"; var rLat = parseFloat(routeObj[r].lat); var rLng = parseFloat(routeObj[r].lng); var rm = L.marker([rLat, rLng], { icon: routeIcon[isR8 ? 0 : 1], title: routeObj[r].name, zIndexOffset: -1100, className: "leaflet-terminator" }).addTo(map); rm.homeLatLng = L.latLng(rLat, rLng); rm.homeRoute = isR8 ? "8" : "18"; rm.homeIndex = nearestKpIndex(isR8 ? kp8_100 : kp18_100, rLat, rLng); routeMarkers.push(rm); } dataReady = true; renderRouteContent(); fitAllRoutes({ animate: false }); if (defaultExtent) { defaultExtent.setCenter(map.getCenter()); defaultExtent.setZoom(map.getZoom()); } } catch (err) { console.error("[chain-map] render error", err); } }).fail(function () { console.log("chain map data load error", arguments); }); })(jQuery);