diff --git a/loc-chase2.js b/loc-chase2.js index 15165d4..6d4a942 100644 --- a/loc-chase2.js +++ b/loc-chase2.js @@ -1,6 +1,8 @@ document.addEventListener("DOMContentLoaded", () => { - var mymap = L.map("locationmap").setView([38.891, 139.824], 16); + const mapDiv = document.getElementById("locationmap"); + + var mymap = L.map(mapDiv).setView([38.891, 139.824], 16); L.tileLayer("https://{s}.tile.osm.org/{z}/{x}/{y}.png", { attribution: @@ -10,11 +12,9 @@ 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"; @@ -28,14 +28,12 @@ watchId = navigator.geolocation.watchPosition( onSuccess, onError, - { maximumAge: 0, timeout: 3000, enableHighAccuracy: true } + { enableHighAccuracy: true } ); document.getElementById("title").textContent = "START!!"; } - - function updateLocation(lat, lng) { - const latlng = L.latLng(lat, lng); + function updateLocation(latlng) { mymap.panTo(latlng); const goalLat = 38.892; @@ -45,7 +43,6 @@ 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) { @@ -60,35 +57,34 @@ .openPopup(); } - function onSuccess(pos) { - updateLocation( + const 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); - } - } + function onError() {} - - mymap.on("mousedown touchstart", function (e) { + mapDiv.addEventListener("mousedown", (e) => { stopLOC(); - updateLocation( - e.latlng.lat, - e.latlng.lng - ); + const latlng = mymap.mouseEventToLatLng(e); + updateLocation(latlng); }); + mapDiv.addEventListener("touchstart", (e) => { + stopLOC(); + const touch = e.touches[0]; + const latlng = mymap.mouseEventToLatLng(touch); + updateLocation(latlng); + }); + + document.getElementById("start") .addEventListener("click", tryWatchLOC); document.getElementById("stop") .addEventListener("click", stopLOC); -}, false); +});