<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>GNSS宝探し</title>
<!-- Leaflet(CDN) -->
<link
rel="stylesheet"
href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
>
<script
src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
defer
></script>
<!-- 自分のJS -->
<script defer>
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:
'© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(mymap);
var locmarker = L.marker(mymap.getCenter()).addTo(mymap);
locmarker.bindPopup("STARTおしてね").openPopup();
var nTrial = 100;
var watchId = null;
function stopLOC() {
if (watchId != null) {
navigator.geolocation.clearWatch(watchId);
document.getElementById("title").textContent = "stop";
locmarker.setPopupContent("停めました");
}
watchId = null;
}
function tryWatchLOC() {
stopLOC();
watchId = navigator.geolocation.watchPosition(
onSuccess,
onError,
{ maximumAge: 0, timeout: 3000, enableHighAccuracy: true }
);
document.getElementById("title").textContent = "START!!";
}
// 共通処理
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) {
message = "おしい!もう少し!";
} 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();
if (nTrial <= 0) {
navigator.geolocation.clearWatch(watchId);
}
}
// 地図クリック対応
mymap.on("click", function (e) {
console.log("クリック:", e.latlng);
stopLOC();
updateLocation(e.latlng);
});
// スマホタップ対応
mymap.on("tap", function (e) {
console.log("タップ:", e.latlng);
stopLOC();
updateLocation(e.latlng);
});
// ボタン設定
document.getElementById("start")
.addEventListener("click", tryWatchLOC);
document.getElementById("stop")
.addEventListener("click", stopLOC);
}, false);
</script>
<style>
#locationmap {
width: 90vw;
height: 75vw; /* ←元の指定に戻しました */
margin: auto;
}
</style>
</head>
<body>
<h1>たからさがし <span id="title"></span></h1>
<p>
<button id="start" type="button">START</button>
<button id="stop" type="button">STOP</button>
</p>
<div id="locationmap"></div>
</body>
</html>