document.addEventListener("DOMContentLoaded", () => { var koeki = L.map("gpsmap").setView([38.891, 139.824], 16); L.tileLayer( '//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(koeki); var gpsmarker = L.marker(koeki.getCenter()).addTo(koeki); gpsmarker.bindPopup("出発を押してください").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("GPSを止めました"); } 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.89821 && x < 38.898 && y > 139.82024 && y < 139.81976){ ここに書く } } var b = L.geoJson(nanshuujson, { style: function (feature) { return feature.properties; } }); L.control.layers(null, {"nanshuujson": b}).addTo(koeki); var c = L.geoJson(dewajson, { style: function (feature) { return feature.properties; } }); L.control.layers(null, {"dewajson": c}).addTo(koeki); var d = L.geoJson(sakatajson, { style: function (feature) { return feature.properties; } }); L.control.layers(null, {"sakatajson": d}).addTo(koeki); var e = L.geoJson(domonjson, { style: function (feature) { return feature.properties; } }); L.control.layers(null, {"domonjson": e}).addTo(koeki); 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);