<?php
	require("__include-common.php");
	require("../account/__logincheck.php");
	if (!defined("MAPS_FIX_HEIGHT")) {
		define("MAPS_FIX_HEIGHT", 15);
	}
	if (!defined("MAPS_SIDE_BAR_WIDTH")) {
		define("MAPS_SIDE_BAR_WIDTH", "170px");
	}
	if (!defined("MAPS_SIDE_BAR_WIDTH_WORLD_HERITAGE")) {
		define("MAPS_SIDE_BAR_WIDTH_WORLD_HERITAGE", "160px");
	}
	if (!defined("MAPS_SIDE_BAR_HEIGHT")) {
		define("MAPS_SIDE_BAR_HEIGHT", "70%");
	}
	if (!defined("MAPS_LINEPATH_COLOR")) {
		define("MAPS_LINEPATH_COLOR", "#ff4500");
	}
	if (!defined("MAPS_LINEPATH_WEIGHT")) {
		define("MAPS_LINEPATH_WEIGHT", 3);
	}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="author" content="ok.2nd">
<meta name="description" content="gpslog">
<meta name="keywords" content="GPSログView, マップ">
<title>MyHome GPSログView マップ</title>
<style>
* { margin: 0px; padding: 0px; }
html {
	width: 100%;
	height: 100%;
	overflow: hidden;
}
form { margin: 0px; }
img { border: 0px; }
body {
	background-color: #ffffff;
	text-align: left;
	font-size: 84%;
	font-family: "ＭＳ Ｐゴシック",arial,helvetica,clean,sans-serif;
	margin: 0;
	width: 100%;
	height: 100%;
}
#page_body {
	width: 100%;
	height: 100%;
}
#page_contents {
	width: 100%;
	height: 100%;
}
#map_canvas {
	width: 100%;
	height: 100%;
}
#maps_filter {
	clear: both;
	margin: 0 0 0 10px;
	padding: 0;
}
.block {
	clear: both;
}
.block_left {
	float: left;
	text-align: left;
	padding: 0;
}
a:link { color: #2128e0; font-weight: normal; }
a:visited { color: #2128e0; font-weight: normal; }
a:hover { color: #f43316; font-weight: normal; background-color: #ffffc0; }
a:active { color: #f43316; font-weight: normal; background-color: #ffffc0; }
a.unesco_translate:link { color: #ff69b4; font-weight: normal; font-size: 72%; }
a.unesco_translate:visited { color: #ff69b4; font-weight: normal; font-size: 72%; }
a.unesco_translate:hover { color: #ff0000; font-weight: normal; font-size: 72%; }
a.unesco_translate:active { color: #ff0000; font-weight: normal; font-size: 72%; }
.error_msg { color: red; margin: 20px; padding: 0; }
.noramal_msg { color: #000000; margin: 20px; padding: 0; }
<?
	if ($_GET['opt'] == 'wh' || $_GET['opt'] == 'sk' || $_GET['opt'] == 'hs') {
		$side_bar_width = MAPS_SIDE_BAR_WIDTH_WORLD_HERITAGE;
	} else {
		$side_bar_width = MAPS_SIDE_BAR_WIDTH;
	}
?>
#side_bar {
	position: absolute; top: 50px; right: 6px; width: <?= $side_bar_width?>; height: <?= MAPS_SIDE_BAR_HEIGHT ?>;
	border: 1px solid #666; padding: 6px; line-height: 1.4; overflow: scroll;
/*	background: #ffffff; filter: alpha(opacity=75); -moz-opacity:0.75; opacity:0.75; */
	background: url(../images/trans-white.png);
}
#side_bar li {
	white-space: nowrap;
}
#option_box {
	position: absolute; top: 4px; right: 130px; width: 190px; height:11px;
	border: 1px solid #666; padding: 6px; overflow: visible;
	background: #ffffff;
	white-space: nowrap;
	padding: 2px 4px 8px 4px;
}
@media print {
	#option_box { display: none; }
	#side_bar { display: none; }
	#route_navi { display: none; }
	#not_found_box { display: none; }
	#map_canvas { position: absolute; top: 0px; left: 0px; }
}
</style>
<script src="../scripts/jquery.js"></script>
<script src="../scripts/jquery.cookie.js"></script>
<script src="../scripts/ok2nd.js"></script>
</head>
<body onload="initialize()">
<?
	$chks = $_POST['check'];
	if (!$chks) {
		error_exit('1件以上、選択してください。', True, False);
	}
	$chk_id = '';
	foreach($chks as $chk){
		if ($chk_id <> '') $chk_id .= ',';
		$chk_id .= $chk;
	}
	$con = my_mysql_connect(_DB_SCHEMA);
	$sql = "select * from v_gpslog where id_gpslog in (".$chk_id.')';
	$rs = my_mysql_query($sql);
	$row = mysql_num_rows($rs);
	if ($row <> 0) {
		google_maps($rs, $row);
	} else {
		echo "<script type='text/javascript'>function initialize(){}</script>\n";
		error_msg('該当するデータがありません。');
	}
	$con = mysql_close($con);
?>
</body>
</html>
<?php
	exit();
?>
<?php
function google_maps($rs, $row) {
	if (!defined("GETLATLNG_SLEEP_TIME")) {
		define("GETLATLNG_SLEEP_TIME", 200000);	// 0.2秒
	}
?>
<script src="http://maps.google.com/maps/api/js?sensor=false&libraries=panoramio,geometry"></script>
<script>
var map;
var geocoder = null;
var maxLat=-999, minLat=999, maxLng=-999, minLng=999;
var notFound = '';
var current_infowin = null;
function setHeightPercent(elementID, fixHeight) {
	// マップの高さ設定
	//if (document.all) {	// IE
	//	fixHeight += 40;
	//}
	mapsWinHeight = 100 - Math.ceil( fixHeight * 100 / screen.availHeight );
	document.getElementById(elementID).style.height = mapsWinHeight + "%";
}
var panoramioView = false;
var panoramio;
var LinePathUse = false;
var latLngWin;
function initialize() {
//	setHeightPercent('map_canvas', <?= MAPS_FIX_HEIGHT ?>);
	maxLat = -999;
	minLat = 999;
	maxLng = -999;
	minLng = 999;
	var vpoint = Array();
<?php
	$popstr = '';
	$address = '';
	$point_tbl = array();
	while ($rec=mysql_fetch_array($rs)) {
		$name = quote_chg($rec['c_name']);
		$popstr = '<span style="color:#000080">'.date_from_mysql('Y/m/d', $rec['c_date']).' '.date_from_mysql('H:i:s', $rec['c_starttime']).'<br>';
		$popstr .= '≪<b>'.$name.'</b>≫</span><br>';
		if ($rec['c_description'].'' <> '') {
			$popstr .= '<span style="color:#666;">'.str_replace("\r",'',str_replace("\n",'<br>',quote_chg($rec['c_description']))).'</span><br>';
		}
		$popstr .= '<a href="view.php?id='.$rec['id_gpslog'].'" target="_blank">ルート表示</a>';
		$popstr .= '&nbsp;&nbsp;&nbsp;<a href="http://maps.google.co.jp/maps?q='.$rec['c_lat'].','.$rec['c_lng'];
		$popstr .= '" target="_blank">Googleマップ</a>';
		$popstr .= '&nbsp;&nbsp;&nbsp;<a href="../tools/google-maps-earth-v3.php?addr='.$rec['c_lat'].','.$rec['c_lng'];
		$popstr .= '" target="_blank">MapsV3</a><br><br>';
		$popstr .= '距離: '.number_format($rec['c_distance'],3).'km<br>';
		$popstr .= '出発時間: '.date_from_mysql('H:i:s', $rec['c_starttime']).'<br>';
		$popstr .= '到着時間: '.date_from_mysql('H:i:s', $rec['c_stoptime']).'<br>';
		$popstr .= '所要時間: '.date_from_mysql('H:i:s', $rec['c_taketime']).'<br>';
		$popstr .= '平均速度: '.number_format($rec['c_speed_ave'],2).'km/h<br>';
		$popstr .= '最高速度: '.number_format($rec['c_speed_max'],2).'km/h<br>';
		$popstr .= '最高地点: '.$rec['c_height_max'].'m<br>';
		$popstr .= '最低地点: '.$rec['c_height_min'].'m<br>';
		if ($rec['c_markericon'] <> '') {
			$icon = $rec['c_markericon'];
		} else {
			$icon = $rec['c_categoryIcon'];
		}
		$lat = $rec['c_lat'];
		$lng = $rec['c_lng'];
		$point_tbl[] = array(date_from_mysql('Y/m/d', $rec['c_date']).' '.$name, $lat, $lng, $popstr);
	}
	$adr_cnt = 0;
	foreach ($point_tbl as $point) {
?>
		vpoint[<?= $adr_cnt ?>] = Array();
		vpoint[<?= $adr_cnt ?>]["name"] = '<?= $point[0] ?>';
		vpoint[<?= $adr_cnt ?>]["lat"] = <?= $point[1] ?>;
		vpoint[<?= $adr_cnt ?>]["lng"] = <?= $point[2] ?>;
		vpoint[<?= $adr_cnt ?>]["popstr"] = '<?= $point[3] ?>';
		vpoint[<?= $adr_cnt ?>]["status"] = 'OK';
<?php
		++$adr_cnt;
	}
?>
	geocoder = new google.maps.Geocoder();
	for (var ix=0; ix<<?= $adr_cnt ?>; ix++) {
		if (vpoint[ix]["status"] == 'OK') {
			var lat = vpoint[ix]["lat"];
			var lng = vpoint[ix]["lng"];
			if (maxLat < lat) maxLat = lat;
			if (minLat > lat) minLat = lat;
			if (maxLng < lng) maxLng = lng;
			if (minLng > lng) minLng = lng;
		}
	}
	if (minLat == maxLat && minLng == maxLng) {
		minLat -= 0.002;		// 1地点の場合、拡大されすぎるのを抑止するため
		minLng -= 0.002;		// initialize()時点では
		maxLat += 0.002;		// map.fitBounds()後にsetZoom()が効かないため
		maxLng += 0.002;		// Lat, Lngを調整してからfitBounds()する
	}
	southWest = new google.maps.LatLng(minLat,minLng);
	northEast = new google.maps.LatLng(maxLat,maxLng);
	bounds = new google.maps.LatLngBounds(southWest,northEast);
	var myOptions = {
		zoom: 15,
		center: new google.maps.LatLng(minLat + maxLat / 2, minLng + maxLng / 2),
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		disableDoubleClickZoom: false,
		streetViewControl: true
	}
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	panoramio = new google.maps.panoramio.PanoramioLayer();
	latLngWin = new google.maps.InfoWindow();
	google.maps.event.addListener(map, 'click', viewLatLngAddress);
	var lineOptions = {
		strokeColor: "<?= MAPS_LINEPATH_COLOR ?>",
		strokeOpacity: 1.0,
		strokeWeight: <?= MAPS_LINEPATH_WEIGHT ?>
	}
	polyline = new google.maps.Polyline(lineOptions);
	polyline.setMap(map);
	google.maps.event.addListener(map, "click", drawLinePath);
	map.fitBounds(bounds);
	showMarker(vpoint, <?= $adr_cnt ?>);
}
function viewLatLngAddress (e) {
	if (LinePathUse) return;
	var latlng = e.latLng;
	var lat = e.latLng.lat().toString();
	var lng = e.latLng.lng().toString();
	geocoder.geocode({'latLng': latlng}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			if (results[1]) {
				 address = results[1].formatted_address;
			} else {
				 address = ""
			}
		} else {
			address = ""
		}
		// 標高取得
		var elevation = '';
		var locations = [latlng];
		var elevator = new google.maps.ElevationService();
		elevator.getElevationForLocations({
			locations: locations
		}, function(results, status) {
			if (status == google.maps.ElevationStatus.OK) {
				if (results[0].elevation) {
					elevation = results[0].elevation.toFixed(1);
				}
			}
			html = '緯度：' + lat + '<br>';
			html += '経度：' + lng + '<br><br>';
			html += '住所：' + address + '<br><br>';
			html += '<a href="http://maps.google.com/maps?q=' + encodeURL(lat) + ',' + encodeURL(lng);
			html += '" target="_blank">→ Googleマップ</a>&nbsp;&nbsp;&nbsp;&nbsp;';
			html += '<a href="../tools/google-maps-earth-v3.php?addr=' + encodeURL(lat) + ',' + encodeURL(lng);
			html += '" target="_blank">→ MAP V3</a><br><br>';
			html += '標高：' + elevation + 'm<br><br>';
			latLngWin.setContent(html);
			latLngWin.setPosition(latlng);
			latLngWin.open(map);
		});
	 });
}
var side_bar_html = "";
var gmarkers = [];
var markerCnt = 0;
function showMarker(vpoint, cnt) {
	for (var ix=0; ix<cnt; ix++) {
		if (vpoint[ix]["status"] == 'OK') {
			var lat = vpoint[ix]["lat"];
			var lng = vpoint[ix]["lng"];
			createMarker(vpoint[ix]["address"], vpoint[ix]["popstr"], vpoint[ix]["name"], lat, lng, vpoint[ix]["marker"]);
		} else {
			notFound += vpoint[ix]["address"] + '&nbsp;';
		}
	}
	document.getElementById('side_bar').innerHTML = "<ul>"+side_bar_html+"</ul>";
	document.getElementById('not_found').innerHTML = notFound;
}
function createMarker(addr, html, name, lat, lng, image) {
	var infowindow = new google.maps.InfoWindow({
		content: html
	});
	var latlng = new google.maps.LatLng(lat, lng);
	if (image != '') {
		icon = "<?= DIARY_MAPS_ICON_FOLDER ?>"+image;
	} else {
		icon = null;
	}
//	var marker_label = zen2han(name).slice(0, 10);
	var marker_label = name;
	var icon = 'http://chart.apis.google.com/chart?chst=d_bubble_text_small&chld=bb|'+marker_label+'|FFD700|000000';
	var icon_s = new google.maps.MarkerImage(icon);
	icon_s.anchor = new google.maps.Point(0, 24);
	icon_s.scaledSize = new google.maps.Size(str_width(marker_label)*5+20, 28);
	var marker = new google.maps.Marker({
		position: latlng,
		map: map,
		title: name,
		icon: icon_s
	});
	google.maps.event.addListener(marker, 'click', function() {
		if (current_infowin) {
			current_infowin.close();
		}
		infowindow.open(map,marker);
		current_infowin = infowindow;
	});
	gmarkers[markerCnt] = marker;
	side_bar_html += '<li><a href="javascript:myClick(' + markerCnt + ')">' + name + '</a></li>';
	markerCnt++;
}
function myClick(markerCnt) {
	google.maps.event.trigger(gmarkers[markerCnt], 'click');
}
function markerClear() {
	map.clearOverlays();
}
function addressClear() {
	document.getElementById("address").value = '';
}
function LinePathOnOff() {
	if (LinePathUse) {
		LinePathUse = false;
	} else {
		LinePathUse = true;
	}
}
function drawLinePath(event) {
	if (LinePathUse) {
		lpath = polyline.getPath();
		lpath.push(event.latLng);
		kyori = google.maps.geometry.spherical.computeLength(lpath.getArray());
	//	document.getElementById("lineLength").value = kyori.toFixed(1);
		document.getElementById("lineLength").value = num_format(kyori,1);
	}
}
function clearLinePath() {
	polyline.setMap(null);
	var lineOptions = {
		strokeColor: "<?= MAPS_LINEPATH_COLOR ?>",
		strokeOpacity: 1.0,
		strokeWeight: <?= MAPS_LINEPATH_WEIGHT ?>
	}
	polyline = new google.maps.Polyline(lineOptions);
	polyline.setMap(map);
	google.maps.event.addListener(map, "click", drawLinePath);
	document.getElementById("lineLength").value = "";
}
</script>
<div id="map_canvas"></div>
<div id="option_box">
	<label><input id="cb_path" type="checkbox" value="on" onclick="LinePathOnOff()" style="margin:3px 0 0 0;"><span style="vertical-align:top;line-height:18px;">距離:</span></label><span style="font-size:10px;line-height:1.0;margin:0;padding:0;"><input type="text" id="lineLength" style="width:60px;font-size:10px;vertical-align:top;">m</span>
	<input onclick="clearLinePath();" type="button" value="クリア" style="font-size:10px;font-size:8px\9;line-height:1.0;vertical-align:top;">
	<label><input type="checkbox" value="on" onclick="PanoramioOnOff(this)" style="margin:3px 0 0 0;"><span style="vertical-align:top;line-height:18px;">写真</span></label>
<script>
function PanoramioOnOff(me) {
	if (me.checked) {
		panoramio.setMap(map);
	} else {
		panoramio.setMap(null);
	}
}
</script>
</div>
<div id="side_bar">Loading...</div>
<div id="not_found_box">Not found: <span id="not_found" style="color: red;"></span></div>
<?php
}
function getLatLng($address, &$lat, &$lng) {		// Geocoding API V3
	$json = my_file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false');
	$latLng = json_decode($json, true);
	if ($latLng['status'] <> 'OK') return 'NotFound';
	$lat = $latLng['results'][0]['geometry']['location']['lat'];
	$lng = $latLng['results'][0]['geometry']['location']['lng'];
	return 'OK';
}
?>
