var tmap =
    tmap||
    function()
{
    
    var info	= document.getElementById("info"),
	update	= document.getElementById("update"),
	undobtn	= document.getElementById("undo"),
	loadbtn	= document.getElementById("reload"),
	namefld	= document.getElementById("name"),
	descfld	= document.getElementById("desc"),
	rmbtn	= document.getElementById("remove"),
	gpsbtn	= document.getElementById("gps");
    
    function init(logfile) {
	var baseLayer = {};
	var map_osm = new L.tileLayer(			// OpenStretMap
	    'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
		attribution :'&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
		maxZoom: 20, maxNativeZoom: 18
	    });
	baseLayer["OpenStreetMap"] = map_osm;
	
	var map_gsi = new L.tileLayer( 			// 国土地理院
	    'https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png', {
		attribution: "<a href='//www.gsi.go.jp/kikakuchousei/kikakuchousei40182.html' target='_blank'>国土地理院</a>",
		maxZoom: 20, maxNativeZoom: 18
	    });
	baseLayer["地理院地図"] = map_gsi;
	
	var jsonmap = L.map('load-json', {layers: [map_gsi]}).setView([38.93272, 139.82917], 14);
	var mapControl = L.control.layers(baseLayer, null).addTo(jsonmap);
	L.control.scale().addTo(jsonmap);
	var markerLayers = L.featureGroup();
	
	
	// GPS 情報の所得
	var gpsIcon = L.icon({
	    iconUrl: 'img/marker.png',
	    iconAnchor: [12,12]
	});
	var gpsmarker = null;
	function gps_error() {
	    dispInfo("GPS信号取得失敗")
	}
	function gps_success(pos) {
	    dispInfo("GPS")
	    var latlng = L.latLng([pos.coords.latitude, pos.coords.longitude]);
	    jsonmap.panTo(latlng);
	    // 地図の中心を取得した位置に
	    if (!gpsmarker)
		gpsmarker = L.marker(latlng, {icon: gpsIcon}).addTo(jsonmap);
	    else
		gpsmarker.setLatLng(latlng);
	    dispInfo(latlng);
	    gpsbtn.disabled = false;
	}
	gpsbtn.addEventListener('click', function() {
	    gpsbtn.disabled = true;
	    dispInfo("位置取得中...");
	    navigator.geolocation.getCurrentPosition(gps_success, gps_error, {
		// enableHighAccuracy: true,
		timeout:	8000,
		maximumAge:	0000,
	    });
	});

	var popupopenmarker = false;
	function updatePopup(e) {
	    var elem = e.target;
	    if (popupopenmarker) {
		let mk = popupopenmarker.marker,
		    pr = popupopenmarker.props;
		pr.name = elem.value;
		let newmk = mk.toGeoJSON();
		newmk.properties.name = elem.value;
		alert(newmk.properties.name);
		gjl.addData(newmk);
		mk.remove();	// 古いマーカを消して入れ直す
		modifyFlag(true);
	    }
	}
	function rmMarker(e) {
	    var elem = e.target;
	    if (popupopenmarker) {
		var mk = popupopenmarker.marker;
		//alert(mk);
		mk.removeFrom(gjl);
		mk.closePopup();
		mk.remove();
		modifyFlag(true);
	    }
	}
	// geojson外部ファイルの読み込みは次の行
	gjl = omnivore.geojson("./gj/yuzasprings.geojson", null, customLayer);
	// ↑引数は順に: ファイル, 解析オプション, カスタムレイヤ
	mapControl.addOverlay(gjl, "遊佐湧水ポイント");
	update.addEventListener('click', function() {updateGJ(gjl)});
	undobtn.addEventListener('click', function(e) {undoMarker(e)});
	rmbtn.addEventListener('click', rmMarker);
	modifyFlag(false);
	function dispGJ() {
	    var gj = gjl.toGeoJSON();
	    var len = gj.features.length;
	    info.textContent = len + ':' + JSON.stringify(gj);
	}
	gjl.on("ready", function() {	// 'ready' イベントに読み終わったときの処理
	    jsonmap.fitBounds(gjl.getBounds());	// 読み取り失敗時は 'error' イベント
	    dispGJ();
	});
	gjl.addTo(jsonmap);		// マップに足す
	// L.control.layers(baseLayer, {"Triangle": gjl}).addTo(jsonmap);
	jsonmap.on('contextmenu', function(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();
		
	    });
	}
		  }
	init("foo");
    }
}();
