document.addEventListener("DOMContentLoaded", () => {
    var bounds = [[38.894697,139.817363],[38.891412,139.820736]];
    var mymap = L.map("mymap").setView([38.893, 139.819], 19);
    L.tileLayer('https://{s}.tile.osm.org/{z}/{x}/{y}.png', {
	attribution:
	'&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    })//.addTo(mymap);
    L.imageOverlay("image/koeki-map.png", bounds).addTo(mymap);
    mymap.setMaxBounds(bounds);
    
    var gpsmarker = L.marker(mymap.getCenter()).addTo(mymap);
    gpsmarker.bindPopup("START").openPopup();
    var geticon = L.icon({iconUrl:"image/Yellow.png",iconSize:[40,41],iconAnchor:[10,41],popupAnchor:[3,-41]});
    
    var nTrial = 10;
    var point = 0;
    var watchId = null;

    let titen = [];
    let marker = [];
    let judge = [];

    function getCSV(){
	var req = new XMLHttpRequest();
	req.open("get", "koeki.csv",true);
	req.send(null);

	req.onload = function(){
	    convertCSVtoArray(req.responseText);
	}
    }
    function convertCSVtoArray(str) {
	var point = [];
	var tmp = str.split("\n");
	for (var x=1;x<tmp.length;x++){
	    point[x] = tmp[x].split(',');
	    for(var i2=0;i2<point[x].length;i2++){
		if(point[x][i2].match(/\-?\d+(.\d+)?(e[\+\-]d+)?/)){
		    point[x][i2] = parseFloat(point[x][i2].replace('"',''));
		}
	    }
	    titen[x] = L.latLng(point[x]);
	    marker[x] = L.marker(point[x]).addTo(mymap);
	}
    }
    getCSV();
    
    //GPSの取得に関するコード
    function stopGPS() {
	console.log("watchId="+watchId);
	if (watchId != null) {
	    navigator.geolocation.clearWatch(watchId);
	    gpsmarker.setPopupContent("止めました");
	}
	watchId = null;
    }
    function tryWatchGPS() {
	stopGPS();
	watchId = navigator.geolocation.watchPosition(
	    onSuccess,onError,{
		maximumAge: 0, timeout: 3000, enableHighAccuracy: true});
    }
    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();
	for (var i in titen){
	    if (latlng.distanceTo(titen[i]) < 50){
		if (!judge[i]){
		    judge[i] = true;
		    alert("スタンプゲット!!!");
		    let img =document.getElementById(`image${i}`);
		    if(i == 1){
			img.src = "image/cafe.png";
		    }else if(i==2){
			img.src = "image/hall.png";
		    }
		    marker[i].setIcon(geticon);
		}
	    }
	}
    }
    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();
//	    for (var i in titen){
//		if (latlng.distanceTo(titen[i]) < 50){
//		    if (!judge[i]){
//			judge[i] = true;
//			alert("スタンプゲット!!!");
//			let img = document.getElementById(`image${i}`);
//			if(i ==1){
//			    img.src = "image/cafe.png";
//			}else if(i==2){
//			    img.src = "image/hall.png";
//			}
//			marker[i].setIcon(geticon);
//		    }
//		}
//	    }
//	}
 //  });   
    document.getElementById("start").addEventListener("click", tryWatchGPS);
    document.getElementById("stop").addEventListener("click", stopGPS);
}, false);
