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 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)); } 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(); /* if (38.8941<=latlng.lat && latlng.lat<=38.8946) { if (139.8194<=latlng.lng && latlng.lng<=139.8197) { gpsmarker.setPopupContent("GOAL! カフェテリアだよ").openPopup(); } } */ var target = [38.8934,139.82]; if (distance(latlng.lng,latlng.lat,target[1],target[0])<=300) { gpsmarker.setPopupContent("公益大ですよ\nここは lat="+latlng.lat+", lng="+latlng.lng+" です.").openPopup(); } // ★★★★★ ここまでの 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);