document.addEventListener("DOMContentLoaded", () => { var mymap = L.map("gpsmap").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 gpsmarker = L.marker(mymap.getCenter()).addTo(mymap); gpsmarker.bindPopup("STARTおしてね").openPopup(); var nTrial = 100 var watchId = null; // 最初はnullにしておく function stopGPS() { // watchが動いていたら止めてnullにする console.log("watchId="+watchId); if (watchId != null) { // nullかどうかで比較しないとだめ(初期値0) navigator.geolocation.clearWatch(watchId); document.getElementById("title").textContent = "stop"; gpsmarker.setPopupContent("停めました"); } watchId = null; } function tryWatchGPS() { stopGPS(); // 二重で動かないように注意する watchId = navigator.geolocation.watchPosition( onSuccess, onError,{ maximumAge: 0, timeout: 3000, enableHighAccuracy: true}); document.getElementById("title").textContent = "START!!"; } function onSuccess(pos) { // GPS信号が取れたらここに来る var latlng = L.latLng([pos.coords.latitude, pos.coords.longitude]); mymap.panTo(latlng);// 地図の中心をそこにする console.log(latlng); // ★★★★★ ここから gpsmarker.setLatLng(latlng).setPopupContent( "ここは lat="+latlng.lat+", lng="+latlng.lng+" です." ).openPopup(); var x = latlng.lng, y = latlng.lat; if (x >38.894112 && x < 38.894626 && y >139.819404 && y < 139.819694) alert("ごーる!"); } function onError(err) { restN = "あと"+(--nTrial)+"回試行します。"; gpsmarker.setPopupContent("捕捉失敗:"+restN).openPopup(); if (nTrial <= 0) { navigator.geolocation.clearWatch(watchId); } } // STARTボタンに開始を仕込む document.getElementById("start").addEventListener("click", tryWatchGPS); // STOPボタンに停止を仕込む document.getElementById("stop").addEventListener("click", stopGPS); }, false);