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();
// ★★★★★ ここまでの 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);