diff --git a/loc-chase2.js b/loc-chase2.js index 84de72a..6c45c3b 100644 --- a/loc-chase2.js +++ b/loc-chase2.js @@ -1,19 +1,19 @@ document.addEventListener("DOMContentLoaded", () => { + var mymap = L.map("locationmap").setView([38.891, 139.824], 16); - + L.tileLayer("https://{s}.tile.osm.org/{z}/{x}/{y}.png", { attribution: '© OpenStreetMap contributors' }).addTo(mymap); - + var locmarker = L.marker(mymap.getCenter()).addTo(mymap); locmarker.bindPopup("STARTおしてね").openPopup(); - + var nTrial = 100; var watchId = null; - + function stopLOC() { - console.log("watchId=" + watchId); if (watchId != null) { navigator.geolocation.clearWatch(watchId); document.getElementById("title").textContent = "stop"; @@ -21,7 +21,7 @@ } watchId = null; } - + function tryWatchLOC() { stopLOC(); watchId = navigator.geolocation.watchPosition( @@ -31,23 +31,21 @@ ); document.getElementById("title").textContent = "START!!"; } - - function onSuccess(pos) { - var latlng = L.latLng( - pos.coords.latitude, - pos.coords.longitude - ); + + // =================================== + // ★ 共通処理(GPSでもクリックでも使う) + // =================================== + function updateLocation(latlng) { mymap.panTo(latlng); - - // ★★★★★ ここから(課題部分) + const goalLat = 38.892; const goalLng = 139.825; - + const dLat = Math.abs(latlng.lat - goalLat); const dLng = Math.abs(latlng.lng - goalLng); - + let message; - + if (dLat < 0.0003 && dLng < 0.0003) { message = "🎉 GOAL!! 宝を見つけました!"; } else if (dLat < 0.001 && dLng < 0.001) { @@ -55,14 +53,24 @@ } else { message = "探索中…"; } - + locmarker .setLatLng(latlng) .setPopupContent(message) .openPopup(); - // ★★★★★ ここまで } - + + // =================================== + // GPS 成功時 + // =================================== + function onSuccess(pos) { + var latlng = L.latLng( + pos.coords.latitude, + pos.coords.longitude + ); + updateLocation(latlng); + } + function onError(err) { var restN = "あと" + (--nTrial) + "回試行します。"; locmarker.setPopupContent("捕捉失敗:" + restN).openPopup(); @@ -70,11 +78,22 @@ navigator.geolocation.clearWatch(watchId); } } - - // ★ ボタン設定はここ + + // =================================== + // ★ 地図クリック対応(追加部分) + // =================================== + mymap.on("click", function (e) { + stopLOC(); // GPSを止める + updateLocation(e.latlng); // クリック位置で判定 + }); + + // =================================== + // ボタン設定 + // =================================== document.getElementById("start") .addEventListener("click", tryWatchLOC); + document.getElementById("stop") .addEventListener("click", stopLOC); - + }, false);