<?php
	require("__include-common.php");
	require("../account/__logincheck.php");
	if (!defined("gpslog_MARKERPOINT_SELECT")) {
		define("gpslog_MARKERPOINT_SELECT", "1,2,5,10,15,20,30,60,120");
		define("gpslog_MARKERPOINT_SELECT_DEFAULT", "10");
	}
	if ($_COOKIE['gpslog_markerPoint'].'' == '') {
		$_COOKIE['gpslog_markerPoint'] = gpslog_MARKERPOINT_SELECT_DEFAULT;
	}
	if (!defined("gpslog_PLAYSPEED_SELECT")) {
		define("gpslog_PLAYSPEED_SELECT", "1,2,5,10,20,50,100");
		define("gpslog_PLAYSPEED_SELECT_DEFAULT", "5");
	}
	if (!defined("gpslog_CHART_WIDTH")) {
		define("gpslog_CHART_WIDTH", '95%');
	}
	if (!defined("gpslog_CHART_HEIGHT")) {
		define("gpslog_CHART_HEIGHT", '400');
	}
	if (!defined("gpslog_CHART_COLOR_SPEED")) {
		define("gpslog_CHART_COLOR_SPEED", '#CD853F');
	}
	if (!defined("gpslog_CHART_COLOR_HEIGHT")) {
		define("gpslog_CHART_COLOR_HEIGHT", '#89A54E');
	}
	if (!defined("ALBUM_MAPS_PHOTO_ICON_MARKER_SIZE")) {
		define("ALBUM_MAPS_PHOTO_ICON_MARKER_SIZE", "40,40");
	}
	if (!defined("MAPS_PHOTO_MARKER_DRAGGABLE")) {
		define("MAPS_PHOTO_MARKER_DRAGGABLE", "YES");
	}
	if ($_COOKIE['gpslog_playSpeed'].'' == '') {
		$_COOKIE['gpslog_playSpeed'] = gpslog_PLAYSPEED_SELECT_DEFAULT;
	}
	if ($_GET['id'].'' <> '') {
		$id = intval($_GET['id']);
	} else {
		$id = 0;
	}
	if ($_GET['move'].'' <> '') {
		$move = intval($_GET['move']);
	} else {
		$move = -1;
	}
	if ($id == 0 and $move < 0) {
		error_exit("不正アクセス。(1)<br>", False);
	}
	if ($_GET['page'].'' <> '') {
		$page = intval($_GET['page']);
	}
	if ($_GET['row'].'' <> '') {
		$row = intval($_GET['row']);
	}
	if ($_GET['pl'].'' <> '') {
		$pageline = intval($_GET['pl']);
	}
	if ($_GET['ac'].'' <> '') {
		$ac = intval($_GET['ac']);
	}
	$con = my_mysqli_connect(_DB_SCHEMA);
	if ($id == 0) {
		if ($_SESSION['gpslog_list_sql'].'' == '') {
			error_exit("不正アクセス。(2)<br>", False);
		}
		$rs = my_mysqli_query($_SESSION['gpslog_list_sql']);
		if ($rs) {
			if (($row = mysqli_num_rows($rs)) == 0) {
				rec_not_found('データがありません。');
				return;
			}
			if ($row < $move+1) {
				rec_not_found('データがありません。');
				return;
			}
			if (!mysqli_data_seek($rs, $move)) {
				rec_not_found('データがありません。');
				return;
			}
			$rec = mysqli_fetch_array($rs);
			$id = $rec['id_gpslog'];
		}
	} else {
		$sql = "select * from m_gpslog where id_gpslog = ".$id;
		$rs = my_mysqli_query($sql);
		if (mysqli_num_rows($rs) == 0) {
			rec_not_found('データがありません。');
			return;
		}
		$rec = mysqli_fetch_array($rs);
	}
	if ($_GET['mp'].'' <> '') {
		$sql = "update m_gpslog set";
		$sql .= " c_markerpoint = '".$_GET['mp']."'";
		$sql .= " where id_gpslog = ".$id;
		$sql .= " and id_account = ".$_SESSION['current_id'];
		$ret = my_mysqli_query($sql, "更新できませんでした。");
		$rec['c_markerpoint'] = intval($_GET['mp']);
	}
	mysqli_close($con);
	$filename = $rec['c_attachFile1'];
	$filepath = ATTACH_FILE_FOLDER.$_SESSION['current_id'].'/'.$filename;
	if ($rec['c_markerpoint'] <> 0) {
		$markerPoint = $rec['c_markerpoint'];
	} else {
		$markerPoint = $_COOKIE['gpslog_markerPoint'];
	}
	$gpxinfo = gpx_read($filepath, $markerPoint*60, $track, $waypoints, $markerlist, $minLat, $minLng, $maxLat, $maxLng);
	if ($_GET['mode'] == 'new' or $_GET['mode'] == 'upd') {
		if ($gpxinfo['name'].'' <> '') {
			$name = $gpxinfo['name'];
		} else {
			$name = '（なし）';
		}
		if ($_POST['hh1'] <> "") {
			$time1 = "'2008-1-1 ".$_POST['hh1'].":".$_POST['mm1'].":00'";
		} else {
			$time1 = "NULL";
		}
		$con = my_mysqli_connect(_DB_SCHEMA);
		$sql = "update m_gpslog set";
		$sql .= " c_distance = '".str_for_mysql($gpxinfo['dist_total'])."'";
		$sql .= ", c_starttime = '2008-1-1 ".$gpxinfo['start']."'";
		$sql .= ", c_stoptime = '2008-1-1 ".$gpxinfo['stop']."'";
		$sql .= ", c_taketime = '2008-1-1 ".$gpxinfo['time']."'";
		$sql .= ", c_markerpoint = '".$_COOKIE['gpslog_markerPoint']."'";
		$sql .= ", c_speed_ave = '".str_for_mysql($gpxinfo['speed_ave'])."'";
		$sql .= ", c_speed_max = '".str_for_mysql($gpxinfo['speed_max'])."'";
		$sql .= ", c_height_max = '".str_for_mysql($gpxinfo['height_max'])."'";
		$sql .= ", c_height_min = '".str_for_mysql($gpxinfo['height_min'])."'";
		$sql .= ", c_lat = '".str_for_mysql($gpxinfo['start_lat'])."'";
		$sql .= ", c_lng = '".str_for_mysql($gpxinfo['start_lng'])."'";
		$sql .= ", c_updatetime = '". date("Y/m/d H:i:s") . "'";
		if ($_GET['mode'] == 'new') {
			$sql .= ", c_name = '".str_for_mysql($name)."'";
			$sql .= ", c_description = '".str_for_mysql($gpxinfo['desc'])."'";
			$sql .= ", c_date = '".str_for_mysql($gpxinfo['date'])."'";
		}
		$sql .= " where id_gpslog = ".$id;
		$sql .= " and id_account = ".$_SESSION['current_id'];
		$ret = my_mysqli_query($sql, "更新できませんでした。");
		mysqli_close($con);
		if ($_GET['mode'] == 'upd') {
			$gpxinfo['name'] = $rec['c_name'];
			$gpxinfo['desc'] = $rec['c_description'];
			$gpxinfo['date'] = $rec['c_date'];
		}
	} else {
		if ($rec['c_name'] <> '') {
			$gpxinfo['name'] = $rec['c_name'];
		}
		if ($rec['c_description'] <> '') {
			$gpxinfo['desc'] = $rec['c_description'];
		}
		if ($rec['c_date'].'' <> '') {
			$gpxinfo['date'] = $rec['c_date'];
		}
	 	if ($_GET['mp'].'' <> '') {
			$con = my_mysqli_connect(_DB_SCHEMA);
			$sql = "update m_gpslog set";
			$sql .= " c_speed_max = '".str_for_mysql($gpxinfo['speed_max'])."'";
			$sql .= " where id_gpslog = ".$id;
			$sql .= " and id_account = ".$_SESSION['current_id'];
			$ret = my_mysqli_query($sql, "更新できませんでした。");
			$rec['c_markerpoint'] = intval($_GET['mp']);
			mysqli_close($con);
		}
	}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="author" content="ok.2nd">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<title>GPSログ View by 轍(Wadachi)</title>
<link rel="stylesheet" href="<?= _STYLE_SHEET_FOLDER_COMMON ?>/common.css?20131130">
<link rel="stylesheet" type="text/css" href="css/style.css">
<style>
div#chart {
	width: <?= gpslog_CHART_WIDTH ?>;
	margin: 5px 0 0 0;
	padding: 0;
}
</style>
<script src="../scripts/jquery.js"></script>
<script src="../scripts/jquery.cookie.js"></script>
<script src="http://www.google.com/jsapi"></script>
<script src="../scripts/Highcharts/js/highcharts.js"></script>
<script src="../scripts/Highcharts/js/modules/exporting.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="js/googlemaps.js"></script>
<script>
<?php	if ($_COOKIE['gpslog_photoview'] == 'on' and $rec['c_photo_folder'].'' <> '') { ?>
var photo_gps = Array();
<?php
	$photo_cnt = 0;
	$photo_dir = str_replace('//','/',$_SESSION['login_friends_album_calendar_folder_'.$_SESSION['current_id']].'/'.$rec['c_photo_folder']);
	// glob(myfile_ENCODE($photo_dir).'/{*.jpg,*.jpeg}', GLOB_BRACE) では環境(?)によって日本語パスではうまくいかない。
	$files_SJIS = scandir(myfile_ENCODE($photo_dir));
	foreach ($files_SJIS as $file_SJIS) {
		$file = myfile_DECODE($file_SJIS);
		if (is_ext_filename_str($file, 'jpg,jpeg')) {
			$photo_file = $photo_dir.'/'.$file;
			if ($_COOKIE['gpslog_photoadjust'] == 'on') {
				$latLngFunc = "photo_time_latLng";
			} else {
				$latLngFunc = "exif_gps";
			}
			if ($lat_lng = $latLngFunc($photo_file, $gpxinfo['point_ary'])) {
?>
photo_gps[<?= $photo_cnt ?>] = Array();
photo_gps[<?= $photo_cnt ?>]["lat"] = <?= $lat_lng[0] ?>;
photo_gps[<?= $photo_cnt ?>]["lng"] = <?= $lat_lng[1] ?>;
photo_gps[<?= $photo_cnt ?>]["time"] = '<?= $lat_lng[2] ?>';
photo_gps[<?= $photo_cnt ?>]["photo"] = '<?= $photo_file ?>';
<?php
				if ($maxLat < $lat_lng[0]) $maxLat = $lat_lng[0];
				if ($minLat > $lat_lng[0]) $minLat = $lat_lng[0];
				if ($maxLng < $lat_lng[1]) $maxLng = $lat_lng[1];
				if ($minLng > $lat_lng[1]) $minLng = $lat_lng[1];
				$photo_cnt++;
			}
		}
	}
?>
var photo_gps_cnt = <?= $photo_cnt ?>;
var photo_markers = [];
var photo_markerCnt = 0;
function showMarkerPhoto(photo_gps, cnt) {
	for (var ix=0; ix<cnt; ix++) {
		createMarkerPhoto(photo_gps[ix]["lat"], photo_gps[ix]["lng"], photo_gps[ix]["time"], photo_gps[ix]["photo"]);
	}
}
var current_infowin = null;
function createMarkerPhoto(lat, lng, datetime, photo) {
	var icon = null;
	img_src = '../photo/img-view.php?img='+photo;
	var html = '<b>' + datetime + '</b><br>';
	html += '緯度：' + lat + '<br>';
	html += '経度：' + lng + '<br>';
	html += '<a href="http://maps.google.com/maps?q=' + lat + ',' + lng;
	html += '" target="_blank">Googleマップ</a><br><br>';
	html += '<a href="'+img_src+'" target="_blank"><img src="'+img_src+'" height="128"></a>';
	icon = new google.maps.MarkerImage(
		img_src,
		new google.maps.Size(<?= ALBUM_MAPS_PHOTO_ICON_MARKER_SIZE ?>),	// size
		new google.maps.Point(0,0),	// origin
		new google.maps.Point(16,16),	// anchor
		new google.maps.Size(<?= ALBUM_MAPS_PHOTO_ICON_MARKER_SIZE ?>)	// scaledSize
	);
	var infowindow = new google.maps.InfoWindow({
		content: html
	});
	var position = new google.maps.LatLng(lat, lng);
	var photo_marker = new google.maps.Marker({
		icon: icon,
		map: map,
		position: position
<?php if (MAPS_PHOTO_MARKER_DRAGGABLE == 'YES') { ?>
		, draggable: true
<?php	 } ?>
	});
	google.maps.event.addListener(photo_marker, 'click', function() {
		if (current_infowin) {
			current_infowin.close();
		}
		infowindow.open(map,photo_marker);
		current_infowin = infowindow;
	});
	photo_markerCnt++;
	photo_markers[photo_markerCnt] = photo_marker;
}
<?php	} else { ?>
var photo_gps_cnt = 0;
<?php	} ?>
</script>
<script>
var point_max=<?= $gpxinfo['point_num'] ?>;
$(function(){
	var w = document.documentElement.clientWidth;
	var h = document.documentElement.clientHeight;
	$('#map').css('width', parseInt(w) - 230);
	if (chartinFlg == 'in') {
		mapHeight = parseInt(h * 0.7) - 80;
		chartHeight = h - mapHeight - 85;
	} else {
		mapHeight = parseInt(h) - 80;
		chartHeight = <?= gpslog_CHART_HEIGHT ?>;
	}
	$('#map').css('height', mapHeight);
	$('#markerlistbox').css('height', mapHeight);
	$('#chart').css('height', chartHeight);
})
function setWaypoints() {
	<?= $waypoints ?>
}
function setTracks() {
	track[0] = new Array();
	<?= $track ?>
	drawTrack(0, '#FF0000', 3, 0.70);
}
var pantoFlg = '<?= $_COOKIE['gpslog_panTo'] ?>';
function pantoChg() {
	if ($("#panto").attr('checked')) {
		pantoFlg = '';
	} else {
		pantoFlg = 'no';
	}
	$.cookie('gpslog_panTo',pantoFlg,{path:'<?= MY_SESSION_PATH ?>', expires:365});
}
var chartinFlg = '<?= $_COOKIE['gpslog_chartIn'] ?>';
function chartinChg() {
	if ($("#chartin").attr('checked')) {
		chartinFlg = 'in';
	} else {
		chartinFlg = '';
	}
	$.cookie('gpslog_chartIn',chartinFlg,{path:'<?= MY_SESSION_PATH ?>', expires:365});
	location.href = "?id=<?= $_GET['id'] ?>&move=<?= $_GET['move'] ?>&row=<?= $_GET['row'] ?>&page=<?= $_GET['page'] ?>";
}
var photoviewFlg = '<?= $_COOKIE['gpslog_photoview'] ?>';
function photoviewChg() {
	if ($("#photoview").attr('checked')) {
		photoviewFlg = 'on';
	} else {
		photoviewFlg = '';
	}
	$.cookie('gpslog_photoview',photoviewFlg,{path:'<?= MY_SESSION_PATH ?>', expires:365});
	location.href = "?id=<?= $_GET['id'] ?>&move=<?= $_GET['move'] ?>&row=<?= $_GET['row'] ?>&page=<?= $_GET['page'] ?>";
}
var photoadjustFlg = '<?= $_COOKIE['gpslog_photoadjust'] ?>';
function photoadjustChg() {
	if ($("#photoadjust").attr('checked')) {
		photoadjustFlg = 'on';
	} else {
		photoadjustFlg = '';
	}
	$.cookie('gpslog_photoadjust',photoadjustFlg,{path:'<?= MY_SESSION_PATH ?>', expires:365});
	location.href = "?id=<?= $_GET['id'] ?>&move=<?= $_GET['move'] ?>&row=<?= $_GET['row'] ?>&page=<?= $_GET['page'] ?>";
}
function setMarkerPoint() {
	markerPoint = $("#markerPoint").val();
	$.cookie('gpslog_markerPoint',markerPoint,{path:'<?= MY_SESSION_PATH ?>', expires:365});
	location.href = "?mp="+markerPoint+"&id=<?= $_GET['id'] ?>&move=<?= $_GET['move'] ?>&row=<?= $_GET['row'] ?>&page=<?= $_GET['page'] ?>";
}
function setPlaySpeed() {
	playSpeed = $("#playSpeed").val();
	$.cookie('gpslog_playSpeed',playSpeed,{path:'<?= MY_SESSION_PATH ?>', expires:365});
}
</script>
</head>
<body onLoad="displayMap(<?= $minLat ?>, <?= $minLng ?>, <?= $maxLat ?>, <?= $maxLng ?>)">
	<p>
		<a class="a_view_cancel_back" href='list.php?page=<?= $page ?>&arg=session'>一覧に戻る</a>
	<?php if ($move <> -1) { ?>
		<span class="view_page"><span class="view_page_num"><?= $move+1 ?></span> / <span class="view_page_num"><?= $row ?></span></span>
		<?php if ($move <> 0) { ?>
		<a class="a_view_move" href="<?= $_SERVER['SCRIPT_NAME'] ?>?move=0&row=<?= $row ?>&page=<?= $page ?>">[←先頭]</a>
		<a class="a_view_move" href="<?= $_SERVER['SCRIPT_NAME'] ?>?move=<?= $move-1 ?>&row=<?= $row ?>&page=<?= $page ?>">[←前]</a>
		<?php } else { ?>
		<span class="view_link_off">[←先頭]</span>
		<span class="view_link_off">[←前]</span>
		<?php } ?>
		<?php if ($move < $row-1) { ?>
		<a class="a_view_move" href="<?= $_SERVER['SCRIPT_NAME'] ?>?move=<?= $move+1 ?>&row=<?= $row ?>&page=<?= $page ?>">[→次]</a>
		<a class="a_view_move" href="<?= $_SERVER['SCRIPT_NAME'] ?>?move=<?= $row-1 ?>&row=<?= $row ?>&page=<?= $page ?>">[→最後]</a>
		<?php } else { ?>
		<span class="view_link_off">[→次]</span>
		<span class="view_link_off">[→最後]</span>
		<?php } ?>
	<?php } else { ?>
		<a class="a_view_cancel_back" href='input.php' style="margin-left:10px;">新規登録</a>
	<?php } ?>
		<a class="a_update_form" href="edit.php?id=<?= $id ?>&move=<?= $move ?>&row=<?= $row ?>&cat=<?= $_GET['cat'] ?>&key=<?= urlencode($_GET['key']) ?>&sort=<?= $_GET['sort'] ?>&page=<?= $page ?>&pl=<?= $pageline ?>&ret=view&#input">[修正]</a>
		<a href="../tools/google-maps-earth-multi-v3.php?addr=<?= urlencode($gpxinfo['marker_lat_lng']) ?>" target="_blank" style="margin-left:10px;">→MapsV3(複数)</a>
		<?php
			if ($rec['c_photo_folder'].'' <> '') {
				$calendar_folder = $_SESSION['login_friends_album_calendar_folder_'.$_SESSION['current_id']];
				$photo_folder = str_replace('//','/',$calendar_folder.'/'.$rec['c_photo_folder']);
		?>
			<a href="../photo/?path=<?= urlencode($photo_folder) ?>" target="_blank" style="margin-left:10px;">→アルバム</a>
		<?php	} ?>
	</p>
<div id="container" style="width: 100%; height: 100%;">
	<div style="width: 100%;">
	<form class="playroute">
		マーカー間隔：<select id="markerPoint" onchange="setMarkerPoint()">
	<?php
		$mp_ary = explode(",", gpslog_MARKERPOINT_SELECT);
		foreach ($mp_ary as $mp) {
	?>
		<option value="<?= $mp ?>"<?= $markerPoint == $mp ? " selected" : "" ?>><?= $mp ?>分
	<?php
		}
	?>
		</select>
		<input type="button" value="ルート再生" class="playbuttons" onClick="playRoute()">
		<input type="button" value="停止" class="playbuttons" onClick="stopRoute()">
		<input type="button" value="スタート地点" class="playbuttons" onClick="rewindRoute()">
<!--
		<input type="button" value="前トラック" class="playbuttons" onClick="prevTrack()">
		<input type="button" value="次トラック" class="playbuttons" onClick="nextTrack()">
-->
		<select id="playSpeed" class="playbuttons" onchange="setPlaySpeed()">
	<?php
		$playspeedary = explode(",", gpslog_PLAYSPEED_SELECT);
		foreach ($playspeedary as $playspeed) {
	?>
		<option value="<?= $playspeed ?>"<?= $_COOKIE['gpslog_playSpeed'] == $playspeed ? " selected" : "" ?>><?= $playspeed ?>ポイント/秒
	<?php
		}
	?>
		</select>
		<label><input type="checkbox" id="panto" onClick="pantoChg()"<? if ($_COOKIE['gpslog_panTo'].'' <> 'no') echo ' checked'; ?>>ルート再生時に中心移動</label>
		&nbsp;<label><input type="checkbox" id="chartin" onClick="chartinChg()"<? if ($_COOKIE['gpslog_chartIn'].'' == 'in') echo ' checked'; ?>>グラフを画面内に</label>
		&nbsp;<label><input type="checkbox" id="photoview" onClick="photoviewChg()"<? if ($_COOKIE['gpslog_photoview'].'' == 'on') echo ' checked'; ?>>写真表示</label>
		&nbsp;<label><input type="checkbox" id="photoadjust" onClick="photoadjustChg()"<? if ($_COOKIE['gpslog_photoadjust'].'' == 'on') echo ' checked'; ?>>撮影時間から場所を特定</label>
	</form>
	</div>
	<div id="map" style="clear: both"></div>
	<div id="markerlistbox">
		<div class="markerlist_header">
			<span style="font-weight:bold;"><?= date('Y/m/d', strtotime($gpxinfo['date'])) ?></span><br>
			<span style="font-weight:bold;font-size:14px;"><?= my_htmlspecialchars($gpxinfo['name']) ?></span><br>
		<?php if ($gpxinfo['desc'].'' <> '') { ?>
			<span style="color:#404040;"><?= ins_br(my_htmlspecialchars($gpxinfo['desc'])) ?></span><br>
		<?php } ?>
			距離: <?= number_format($gpxinfo['dist_total'],3) ?> km<br>
			出発時間: <?= $gpxinfo['start'] ?><br>
			到着時間: <?= $gpxinfo['stop'] ?><br>
			所要時間: <?= $gpxinfo['time'] ?><br>
			平均速度: <?= number_format($gpxinfo['speed_ave'],2) ?> km/h<br>
			最高速度: <?= number_format($gpxinfo['speed_max'],2) ?> km/h<br>
			最高地点: <?= $gpxinfo['height_max'] ?> m<br>
			最低地点: <?= $gpxinfo['height_min'] ?> m<br>
		</div>
		<ul class="markerlist">
		<?= $markerlist ?>
		</ul>
	</div>
<!-- 著作権表示：削除禁止ここから -->
<div class="copyright" style="clear:both;"><a href="http://wadachi.cyclekikou.net/" target="_blank">Powered by Wadachi</a></div>
<!-- 著作権表示：削除禁止ここまで -->
</div>
<div id="chart"></div>
<script>
$(function(){
	var chart;
	$(document).ready(function() {
		chart = new Highcharts.Chart({
			chart: {
				renderTo: 'chart',
				zoomType: 'xy'
			},
			title: {
				text: '<b><?= date('Y/m/d', strtotime($gpxinfo['date'])) ?></b> <b><?= str_replace('<','＜',str_replace('>','＞',quote_chg($gpxinfo['name']))) ?></b> <?= str_replace("\n",'',str_replace("\r",'',str_replace('<','＜',str_replace('>','＞',quote_chg($gpxinfo['desc']))))) ?>'
			},
			subtitle: {
				text: '<?= $gpxinfo['start'] ?>～<?= $gpxinfo['stop'] ?> 所要時間:<?= $gpxinfo['time'] ?> 距離:<?= number_format($gpxinfo['dist_total'],3) ?>km 平均速度:<?= number_format($gpxinfo['speed_ave'],2) ?>km/h 最高地点:<?= $gpxinfo['height_max'] ?>m 最低地点:<?= $gpxinfo['height_min'] ?>m'
			},
			xAxis: {
				type: 'datetime'
			},
			yAxis: [{ // Primary yAxis
				title: {
					text: '標高',
					style: {
						color: '<?= gpslog_CHART_COLOR_HEIGHT ?>'
					}
				},
				labels: {
					formatter: function() {
						return this.value +' m';
					},
					style: {
						color: '<?= gpslog_CHART_COLOR_HEIGHT ?>'
					}
				}
			}, { // Secondary yAxis
				gridLineWidth: 0,
				title: {
					text: '速度',
					style: {
						color: '<?= gpslog_CHART_COLOR_SPEED ?>'
					}
				},
				labels: {
					formatter: function() {
						return this.value +' km/h';
					},
					style: {
						color: '<?= gpslog_CHART_COLOR_SPEED ?>'
					}
				},
				opposite: true
			}],
			tooltip: {
				formatter: function() {
					var dt = Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x);
					var unit = {
						'速度': 'km/h',
						'標高': 'm'
					}[this.series.name];
					return '<b>' + dt +'</b><br><b>'+ this.y + '</b> ' + unit;
				}
			},
			legend: {
				layout: 'vertical',
				align: 'left',
			/*	x: 120, */
				verticalAlign: 'top',
			/*	y: 80, */
				floating: true,
				backgroundColor: '#FFFFFF'
			},
			plotOptions: {
				area: {
					fillColor: {
						linearGradient: {x1:0, y1:0, x2:0, y2:1},
						stops: [
							[0, '<?= gpslog_CHART_COLOR_HEIGHT ?>'],
							[1, 'rgba(0,30,0,0)']
						]
					},
					lineWidth: 1,
					marker: {
						enabled: false,
						states: {
							hover: {
								enabled: true,
								radius: 5
							}
						}
					},
					shadow: false,
					states: {
						hover: {
							lineWidth: 1
						}
					},
					threshold: null
				},
				spline: {
					lineWidth: 1,
					marker: {
						enabled: false,
					}
				}
			},
			series: [{
				name: '速度',
				color: '<?= gpslog_CHART_COLOR_SPEED ?>',
				type: 'spline',
				yAxis: 1,
				data: [<?= $gpxinfo['chart_speed'] ?>]
			}, {
				name: '標高',
				color: '<?= gpslog_CHART_COLOR_HEIGHT ?>',
				type: 'area',
				data: [<?= $gpxinfo['chart_ele'] ?>]
			}]
		});
	});
});
</script>
</body>
</html>
<?php
function gpx_read($path, $markerPoint_sec, &$track, &$waypoints, &$markerlist, &$minLat, &$minLng, &$maxLat, &$maxLng) {
	$gpxinfo = array();
	$point_ary = array();
	$minLat = 999;
	$minLng = 999;
	$maxLng = -999;
	$maxLat = -999;
	$gpx = myfile_file_get_contents($path);
	$gpx = mb_convert_encoding($gpx, 'UTF-8', MB_CONVERT_ENCODING_AUTO);
	$gpx_array = simplexml_load_string($gpx);
	$cnt = 0;
	$marker_cnt = 0;
	$marker_dist = 0;
	$pre_time = 0;
	$pre_marker_time = 0;
	$dist_total = 0;
	$height_max = -5000;
	$height_min = 5000;
	$chart_speed = '';
	$chart_ele = '';
	$marker_lat_lng = '';
	foreach ($gpx_array->metadata as $metadata) {
		$gpxinfo['name'] = $metadata->name;	// GeoTracker
	}
	foreach ($gpx_array->trk as $trk) {
	//	$gpxinfo['name'] = $trk->name;		// My Tracks
		$gpxinfo['desc'] = $trk->desc;
		foreach ($trk->trkseg as $trkseg) {
			foreach ($trkseg->trkpt as $trkpt) {
				$lat = (float)$trkpt['lat'];
				$lng = (float)$trkpt['lon'];
				$time = strtotime($trkpt->time);
				if ($cnt == 0) {
					$gpxinfo['date'] = date('Y/m/d', $time);
					$time_start = $time;
					$dist = 0;
					$speed = 0;
					$gpxinfo['start_lat'] = $lat;
					$gpxinfo['start_lng'] = $lng;
					$dist_total = 0;
					$speed_point = 0;
				} else {
					$dist = location_distance($lat, $lng, $pre_lat, $pre_lng) / 1000;
					$marker_dist += $dist;
					$dist_total += $dist;
					$speed = round(($dist) * 3600 / ($time - $pre_time), 3);
					$speed_point = round(($dist_total) * 3600 / ($time - $time_start), 3);
				}
				$time_stop = $time;
				$height = intval($trkpt->ele);
				if ($height_max < $height) $height_max = $height;
				if ($height_min > $height) $height_min = $height;
				$lat_s = $trkpt['lat'];
				$lon_s = $trkpt['lon'];
				$ele_s = $trkpt->ele;
				$track .= 'track[0].push(new TrackPoint('.$lat_s.', '.$lon_s.', '.$dist.', '.(floatval($ele_s)/1000).', '.$speed.', 0, 0, "'.date('D M j Y H:i:s', $time).'", '.$dist_total.', '.$speed_point.'));'."\n";
				$point_ary[] = array($lat_s, $lon_s, $time);
				if ($maxLat < $lat) $maxLat = $lat;
				if ($minLat > $lat) $minLat = $lat;
				if ($maxLng < $lng) $maxLng = $lng;
				if ($minLng > $lng) $minLng = $lng;
				if (($time - $pre_marker_time) > $markerPoint_sec) {
					if ($pre_marker_time <> 0) {
						$marker_speed = round(($marker_dist) * 3600 / ($time - $pre_marker_time), 2);
						$marker_speed_from_start = round(($dist_total) * 3600 / ($time - $time_start), 2);
						if ($marker_speed > $marker_speed_max) {
							$marker_speed_max = $marker_speed;
						}
						$markerlist .= number_format($marker_dist,3).'km '.number_format($marker_speed,2).'km/h</li>';
					} else {
						$marker_speed = 0;
						$marker_speed_from_start = 0;
						$marker_speed_max = 0;
					}
					$marker_lat_lng .= $lat_s.','.$lon_s.' ';
					$waypoints .= 'waypoints.push(new MarkerInfo('.$lat_s.', '.$lon_s.', '.$ele_s.', "'.date('Y/m/d', $time).'", "'.date('H:i:s', $time).'", 0, "'.date('H:i:s', $time).' '.round($dist_total,3).'km", "", "", "", "",'.$cnt.','.round($marker_dist,3).','.$marker_speed.','.round($dist_total,3).','.$marker_speed_from_start.'));'."\n";
					$markerlist .= '<li><a href="javascript:void(0)" onClick="popupMarker('.$marker_cnt.','.$cnt.')">'.($marker_cnt).': '.date('H:i:s', $time).'</a>'."\n";
					$marker_dist = 0;
					$pre_marker_time = $time;
					$marker_cnt++;
				}
				$time_msec = ($time+(9*60*60))*1000;
				$chart_speed .= '['.($time_msec).','.round($speed,2).'],';
				$chart_ele .= '['.($time_msec).','.round($ele_s,2).'],';
				$cnt++;
				$pre_time = $time;
				$pre_lat = $lat;
				$pre_lng = $lng;
			}
		}
	}
	/* 最後のマーカー */
	$marker_speed = round(($marker_dist) * 3600 / ($time - $pre_marker_time), 2);
	$marker_speed_from_start = round(($dist_total) * 3600 / ($time - $time_start), 2);
	if ($marker_speed > $marker_speed_max) {
		$marker_speed_max = $marker_speed;
	}
	$marker_lat_lng .= $lat_s.','.$lon_s;
	$markerlist .= number_format($marker_dist,3).'km '.number_format($marker_speed,2).'km/h</li>';
	$waypoints .= 'waypoints.push(new MarkerInfo('.$lat_s.', '.$lon_s.', '.$ele_s.', "'.date('Y/m/d', $time).'", "'.date('H:i:s', $time).'", 0, "'.date('H:i:s', $time).' '.round($dist_total,3).'km", "", "", "", "",'.$cnt.','.round($marker_dist,3).','.$marker_speed.','.round($dist_total,3).','.$marker_speed_from_start.'));'."\n";
	$markerlist .= '<li><a href="javascript:void(0)" onClick="popupMarker('.$marker_cnt.','.$cnt.')">'.($marker_cnt).': '.date('H:i:s', $time).'</a></li>'."\n";
	$gpxinfo['start'] = date('H:i:s', $time_start);
	$gpxinfo['stop'] = date('H:i:s', $time_stop);
	$gpxinfo['time'] = date('H:i:s', $time_stop - $time_start - (9*60*60));	// 9*60*60: 東京時間調整
	$gpxinfo['dist_total'] = round($dist_total, 3);
	$gpxinfo['speed_ave'] = round(($dist_total) * 3600 / ($time_stop - $time_start), 2);
	$gpxinfo['speed_max'] = $marker_speed_max;
	$gpxinfo['height_max'] = $height_max;
	$gpxinfo['height_min'] = $height_min;
	$gpxinfo['point_num'] = $cnt;
	$time_msec = ($time+(9*60*60))*1000;
	$gpxinfo['chart_speed'] = $chart_speed.'['.($time_msec).','.round($speed,2).']';
	$gpxinfo['chart_ele'] = $chart_ele.'['.($time_msec).','.round($ele_s,2).']';
	$gpxinfo['marker_lat_lng'] = $marker_lat_lng;
	$gpxinfo['point_ary'] = $point_ary;
	return $gpxinfo;
}
function location_distance($lat1, $lon1, $lat2, $lon2) {
	// By http://d.hatena.ne.jp/kudakurage/20100319/1268986000
	// GPSなどの緯度経度の２点間の直線距離を求めるPHP関数 - くらげだらけ
	$lat_average = deg2rad( $lat1 + (($lat2 - $lat1) / 2) );//２点の緯度の平均
	$lat_difference = deg2rad( $lat1 - $lat2 );//２点の緯度差
	$lon_difference = deg2rad( $lon1 - $lon2 );//２点の経度差
	$curvature_radius_tmp = 1 - 0.00669438 * pow(sin($lat_average), 2);
	$meridian_curvature_radius = 6335439.327 / sqrt(pow($curvature_radius_tmp, 3));//子午線曲率半径
	$prime_vertical_circle_curvature_radius = 6378137 / sqrt($curvature_radius_tmp);//卯酉線曲率半径
	//２点間の距離
	$distance = pow($meridian_curvature_radius * $lat_difference, 2) + pow($prime_vertical_circle_curvature_radius * cos($lat_average) * $lon_difference, 2);
	$distance = sqrt($distance);
	
	$distance_unit = round($distance);
	if($distance_unit < 1000){//1000m以下ならメートル表記
		$distance_unit = $distance_unit."m";
	}else{//1000m以上ならkm表記
		$distance_unit = round($distance_unit / 100);
		$distance_unit = ($distance_unit / 10)."km";
	}
	//$hoge['distance']で小数点付きの直線距離を返す（メートル）
	//$hoge['distance_unit']で整形された直線距離を返す（1000m以下ならメートルで記述 例：836m ｜ 1000m以下は小数点第一位以上の数をkmで記述 例：2.8km）
	//return array("distance" => $distance, "distance_unit" => $distance_unit);
	return $distance;
}
function exif_gps($file, $point_ary) {
	$exif = @exif_read_data(myfile_ENCODE($file));
	if (!$exif) {
		return false;
	}
	if ($exif['GPSLatitude'] and $exif['GPSLongitude']) {
		$lat = gps_degree($exif['GPSLatitude'], $exif['GPSLatitudeRef']);
		$lng = gps_degree($exif['GPSLongitude'], $exif['GPSLongitudeRef']);
		if ($exif['GPS']['GPSMapDatum'] == 'TOKYO') {
			TOKYO_to_WGS84($lng, $lng);
		}
		if ($lat and $lng) {
			return array($lat, $lng, $exif['DateTimeOriginal']);
		} else {
			return false;
		}
	}
	return false;
}
function TOKYO_to_WGS84(&$lat, &$lng) {
	// 測地系変換: 日本測地系→世界測地系
	$lat = $lat - $lat * 0.00010695 + $lng * 0.000017464 + 0.0046017;
	$lng = $lng - $lat * 0.000046038 - $lng * 0.000083043 + 0.010040;
}
function photo_time_latLng($file, $point_ary) {
	$exif = @exif_read_data(myfile_ENCODE($file));
	if (!$exif) {
		return false;
	}
	if ($latLng = adjust_latLng($exif, $point_ary)) {
		return array($latLng[0], $latLng[1], $exif['DateTimeOriginal']);
	}
	return false;
}
function adjust_latLng($exif, $point_ary) {
	// $point_ary[][0]: lat
	// $point_ary[][1]: lng
	// $point_ary[][2]: time
	if (!$exif['DateTimeOriginal']) {
		return false;
	}
	$photoTime = strtotime($exif['DateTimeOriginal']);
	if ($photoTime < $point_ary[0][2] or $photoTime > $point_ary[count($point_ary)-1][2]) {
		// 写真撮影時間がGPSログ時間範囲外
		return false;
	}
	foreach ($point_ary as $point) {
		if ($photoTime <= $point[2]) {
			return array($point[0], $point[1]);
		}
	}
	return false;
}
function gps_degree($gps, $ref) {
	if (count($gps) != 3) return false;
	if ($ref == 'S' or $ref == 'W') {
		$pm = -1;
	} else {
		$pm = 1;
	}
	$degree = fraction2number($gps[0])*1;
	$minute = fraction2number($gps[1])*1;
	$second = fraction2number($gps[2])/100;
	return ($degree + $minute/60 + $second/3600) * $pm;
}
function fraction2number($value) {
	$fraction = explode('/', $value);
	if (count($fraction) != 2) return 0;
	return (double)$fraction[0] / (double)$fraction[1];
}
?>
