diff --git a/js/button.js b/js/button.js index 14ad298..de683d8 100644 --- a/js/button.js +++ b/js/button.js @@ -18,7 +18,7 @@ // 既存のマーカー削除 markers.forEach(marker => map.removeLayer(marker)); - markers = []; // 初期化 + markers = []; if (currentRouteLayer) { map.removeLayer(currentRouteLayer); currentRouteLayer = null; @@ -96,25 +96,38 @@ `); - marker.on('popupopen', function (e) { + // ↓↓↓ ポップアップが開いた時にボタンイベントを登録 + marker.on('popupopen', function () { const routeBtn = document.querySelector('.routeBtn'); const resetBtn = document.querySelector('.resetBtn'); - if (routeBtn) { - routeBtn.addEventListener('click', function () { + // 既存のイベントが複数登録されないように一度クリア(安全対策) + routeBtn?.replaceWith(routeBtn.cloneNode(true)); + resetBtn?.replaceWith(resetBtn.cloneNode(true)); + + const newRouteBtn = document.querySelector('.routeBtn'); + const newResetBtn = document.querySelector('.resetBtn'); + + if (newRouteBtn) { + newRouteBtn.addEventListener('click', function () { if (currentRouteLayer) { map.removeLayer(currentRouteLayer); } - const latlng = marker.getLatLng(); - const userLocation = map.getCenter(); // 現在地を取得(ここはmap.getCenter()仮) - - // 仮の直線ルートを描画 - currentRouteLayer = L.polyline([userLocation, latlng], { color: 'blue' }).addTo(map); + + navigator.geolocation.getCurrentPosition(function (position) { + const userLatLng = L.latLng(position.coords.latitude, position.coords.longitude); + const destLatLng = marker.getLatLng(); + + currentRouteLayer = L.polyline([userLatLng, destLatLng], { color: 'blue' }).addTo(map); + map.fitBounds([userLatLng, destLatLng]); + }, function (error) { + alert("現在地を取得できませんでした: " + error.message); + }); }); } - if (resetBtn) { - resetBtn.addEventListener('click', function () { + if (newResetBtn) { + newResetBtn.addEventListener('click', function () { if (currentRouteLayer) { map.removeLayer(currentRouteLayer); currentRouteLayer = null;