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); function distance(x1, y1, x2, y2) { // ヒュベニ式による距離概算 rx = 6378137; // 赤道半径(m) WGS84 ry = 6356752.314; // 極半径(m) WGS84 e2=(rx*rx-ry*ry)/rx/rx; // 離心率 E^2 dx = (x2-x1)*Math.PI/180; // 経度の差をラジアン変換 dy = (y2-y1)*Math.PI/180; // 緯度の差をラジアン変換 my = (y1+y2)/2.0*Math.PI/180; // 緯度の平均をラジアン変換 w = Math.sqrt(1-e2*Math.sin(my)*Math.sin(my)); m = rx*(1-e2)/Math.pow(w,3); // 子午線曲率半径 n = rx/w; // 卯酉線曲率半径 return Math.sqrt(Math.pow(dy*m,2) + Math.pow(dx*n*Math.cos(my),2)); } 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(); let lng1 = latlng.lng, lat1 = latlng.lat, lng2 = 139.819192, lat2 = 38.892463; lat d = distance(lng1, lat1, lang2, lat2); info.innerHTML = "距離: "+Math/round(d*100)/100+"m"; if (Math/round(d*100)/10 <= 50){ alert("ゴール!"); } // ★★★★★ ここまでの latlng.lat と latlng.lng を // if文などで判定して、特定の場所に近づいたら「GOAL!」と // 表示するように変えてみよ。 } 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);