diff --git a/loc-chase2.js b/loc-chase2.js index 3377333..84de72a 100644 --- a/loc-chase2.js +++ b/loc-chase2.js @@ -1,22 +1,19 @@ document.addEventListener("DOMContentLoaded", () => { - const mapDiv = document.getElementById("locationmap"); - - // 地図の初期化 - var mymap = L.map(mapDiv).setView([38.891, 139.824], 16); - + 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"; @@ -24,30 +21,33 @@ } watchId = null; } - - // 位置計測を開始する関数 + function tryWatchLOC() { stopLOC(); watchId = navigator.geolocation.watchPosition( onSuccess, onError, - { enableHighAccuracy: true } + { maximumAge: 0, timeout: 3000, enableHighAccuracy: true } ); document.getElementById("title").textContent = "START!!"; } - - // 位置情報を更新し、判定を行う関数 - function updateLocation(latlng) { + + function onSuccess(pos) { + var latlng = L.latLng( + pos.coords.latitude, + pos.coords.longitude + ); 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,39 +55,26 @@ } else { message = "探索中…"; } - + locmarker .setLatLng(latlng) .setPopupContent(message) .openPopup(); + // ★★★★★ ここまで } - - // GPS取得成功時 - function onSuccess(pos) { - const latlng = L.latLng( - pos.coords.latitude, - pos.coords.longitude - ); - updateLocation(latlng); - } - - // GPS取得失敗時 + function onError(err) { - console.warn(`ERROR(${err.code}): ${err.message}`); + var restN = "あと" + (--nTrial) + "回試行します。"; + locmarker.setPopupContent("捕捉失敗:" + restN).openPopup(); + if (nTrial <= 0) { + navigator.geolocation.clearWatch(watchId); + } } - - // --- 【重要】クリック・タップイベントの統合 --- - // Leafletのmapオブジェクトに対して 'click' を設定すると - // スマホのタップもPCのクリックも両方反応します。 - mymap.on("click", (e) => { - stopLOC(); // 手動操作時はGPS追跡を止める - updateLocation(e.latlng); // クリックした地点の座標(e.latlng)を使用 - }); - - // ボタンのイベントリスナー + + // ★ ボタン設定はここ document.getElementById("start") .addEventListener("click", tryWatchLOC); - document.getElementById("stop") .addEventListener("click", stopLOC); -}); + +}, false);