document.addEventListener("DOMContentLoaded", () => {
    var mymap = L.map("mymap").setView([38.919, 139.828], 17);
    L.tileLayer('https://{s}.tile.osm.org/{z}/{x}/{y}.png', {
	attribution:
	'&copy; <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 = 10
    var watchId = null;
    function stopGPS() {
	console.log("watchId="+watchId);
	if (watchId != null) {
	    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) {
	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();
    }
    function onError(err) {
	restN = "あと"+(--nTrial)+"回試行します";
	gpsmarker.setPopupContent("捕捉失敗:"+restN).openPopup();
	if (nTrial <= 0) {
	    navigator.geolocation.clearWatch(watchId);
	}
    }
    mymap.options.singleClickTimeout = 250;
    mymap.on('singleclick', function(e) {
	if (true){
	    latlng = L.latLng(e.latlng);
	    gpsmarker.setLatLng(e.latlng);
	    mymap.panTo(e.latlng);
	    console.log(e.latlng);
	    gpsmarker.setLatLng(e.latlng).setPopupContent(
		"lat="+latlng.lat+", lng="+latlng.lng+""
	    ).openPopup();
	}
	var x =L.latLng([38.919212, 139.828072]);
	console.log(latlng.distanceTo(x));
	if (latlng.distanceTo(x) < 30) {
	    alert("スタンプゲット!!");
	}
    });
    
    document.getElementById("start").addEventListener("click", tryWatchGPS);
    document.getElementById("stop").addEventListener("click", stopGPS);
}, false);
