
// ajaxを使い、csvを読み込む
// $(document).ready(function() {
//     $.ajax({
// 	type: "GET",
// 	url: "./pstore/data.csv",
// 	dataType: "text",
// 	success: function(data){okiro(data)}
//     });
// });

function okiro(){
    // data = $.csv.toObjects(Text);
    var timerInterval = 10000;	// GPS失敗で何秒後に再取得か
    var tmId = null;
    var nn = 0, countD = document.getElementById("countdown");
    
    // make a map//////////////////////////////////////////////
    var osm =
	L.tileLayer('//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
	    attribution:
	    '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
	    maxZoom: 20, maxNativeZoom: 18
	});
    // var kokudo =
    //     L.tileLayer('//cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png', {
    //       attribution:
    //       '<a href="http://maps.gsi.go.jp/development/ichiran.html">kokudo</a>'
    //     });
    var geomap = L.map("mymap").setView([38.893, 139.8193], 16);
    osm.addTo(geomap);
    var baseLayers = {'OpenStreetMap': osm };
    L.control.layers(baseLayers).addTo(geomap);
    ////////////////////////////////////////////////////////////////
    
    var point = L.marker(geomap.getCenter()).addTo(geomap);
    var stop = document.getElementById("stp");
    var gps = document.getElementById("str");
    var ser = document.getElementById("serif");
    var tm = document.getElementById("time");
    var nowTrying = null;
    
    /*
      var m1 = L.marker([39,140]).addTo(geomap)
    */
    
    function tryGetGPS() {
	clearTimer();
	countD.textContent = "START!"
	ser.textContent = "get GPS..."
	nowTrying = navigator.geolocation.getCurrentPosition(
    	    onSuccess, onError,{
    		maximumAge: 0, timeout: 3000, enableHighAccuracy: true})
    }
    
    function onemore() {
	if (nowTrying || tmId) {
	    info.textContent = "It already getting a GPS ...or 待機中です。";
	} else {
	    startTimer();
	}
    }
    function startTimer() {
	if (tmId==null){
    	    tmId = setTimeout(tryGetGPS, 5000);
    	    ser.textContent = "5秒後にGPS取得…";
	    tm.textConent = "ok";
    	}
    }
    function clearTimer() {
     	if (tmId) {
	    clearTimeout(tmId);
	    tmId = null;
	}
    }

    function countDown() {
	tryGetGPS();
    }
    
    function stopCountDown() {
	clearTimeout();
	countD.textContent = "stop";
     	ser.innerHTML = "startボタンをもう一度押すと始まります";
    }

    function onSuccess(pos) {
	nowTrying = null;
	// var pulsingIcon = L.icon.pulse({iconSize:[20,20],color:'#1199fb'});
	var latlng = L.latLng([pos.coords.latitude, pos.coords.longitude]);
	ser.textContent = "現在の位置は"+latlng+"です。";
	geomap.panTo(latlng);
	// L.marker([lat, lng],{icon: pulsingIcon}).addTo(geomap);
	point.setPopupContent("now").openPopup().setLatLng(latlng);
	var lat = latlng.lat, lng = latlng.lng;
    }
    function onError(err) {			// 失敗時
	nowTrying = null;
	ser.textContent = "現在位置の取得失敗.10秒後にもう一回";
	tmId = setTimeout(tryGetGPS, timerInterval);
    }
    
    
    function onMapClick(e){
	var marker = L.marker(e.latlng,{
	    draggable: true,
	    title: "Resouse location",
	    alt: "Resouce location",
	    riseOnHover: true
	}).addTo(geomap).bindPopup(e.latlng.toString()).openPopup();
	
	marker.on("dragged", function (ev){
	    var cangedPos = ev.target.getLatlng();
	    this.bindPopup(changedPos.toString()).openPopup();
	    
	})
    }
    
    geomap.on('click', onMapClick);

    
    geomap.on("click", function(geotag) {
	var form = document.forms.geotag;
	var idokeido = document.getElementById("gps");
	geotagcopy = "exiftool -gpslatitude="+geotag.latlng.lat+" -gpslatitudeRef=N -gpslongitude="+geotag.latlng.lng+" -gpslongitudeRef=E";
	
	form.lati.value = geotagcopy;           
    });
    /*
      idokeido.textContent = geotagcopy;
    */
    
    geomap.on("click",function(geopop) {
	var popup = L.popup();
	popup.setLatLng(geopop.latlng)
	    .setContent("" + geopop.latlng.toString()).openOn(geomap);
    });


    // data_array= [0,0,0]; //create it before filling
    // for (i = 0; i < data.length; i++) {
    // 	//地図上に表示するデータの設定
    // 	data_array[i] = [parseFloat(data[i].latitude), parseFloat(data[i].longitude), parseFloat(data[i].mag)]; // if values are marked as string in the object else:
    // 	//  data_array[i] = [data[i].lat,data[i].lon,data[i].val];
    // 	var heat = L.marker([(data[i].latitude), (data[i].longitude)],{
    // 	    //ポップアップの内容
    // 	}).bindPopup((data[i].mag)).addTo(geomap);
    // };
    
    var testlayer = new L.GeoJSON.AJAX("../test.geojson",{
    	onEachFeature: function(j, layer) {
    	    let p = j.properties;
    	    if (p) {
    		let name = p.name, desc = p.description;
    		if (p.name) {
    		    if (desc) {
    			// {{画像URL}} → <img src="画像URL"> に置換する
    			desc = desc.replace(/{{(.*)}}/, '<img src="$1">')
    		    }
    		    let popup = "<h3>" + name + "</h3>" + "<p>" + desc + "</p>";
    		    layer.bindPopup(popup);
    		}
    	    }
    	}});
    testlayer.addTo(geomap);
    testlayer.on('data:loaded', function() {
    	jsonmap.fitBounds(testlayer.getBounds());
    	// alert(JSON.stringify(testlayer.toGeoJSON()));
    	// testlayer.toGeoJSON() で元のGeoJSONが得られる
    });
    
    
    
    gps.addEventListener("click",countDown , false);
    stop.addEventListener("click", stopCountDown, false);
};
document.addEventListener("DOMContentLoaded", okiro, false);
