<?php
	require("../__common__/__define_common.php");
	if (!defined("GOOGLE_MAPS_EARTH_ADDRESS")) {
		define("GOOGLE_MAPS_EARTH_ADDRESS", "新宿");
	}
	if (!defined("GOOGLE_MAPS_EARTH_ZOOM")) {
		define("GOOGLE_MAPS_EARTH_ZOOM", 15);
	}
	if (!defined("MAPS_FIX_HEIGHT")) {
		define("MAPS_FIX_HEIGHT", 24);
	}
	if (!defined("MAPS_PHOTO_ICON_MARKER_SIZE")) {
		define("MAPS_PHOTO_ICON_MARKER_SIZE", "64,64");
	}
	if ($_GET['addr'] <> '') {
		$addr = $_GET['addr'];
	} elseif ($_POST['address'] <> '') {
		$addr = $_POST['address'];
	} elseif ($_COOKIE['google_maps_address'] <> '') {
		$addr = $_COOKIE['google_maps_address'];
	} else {
		$addr = GOOGLE_MAPS_EARTH_ADDRESS;
	}
	setcookie('google_maps_address', $addr, time() + LOGIN_COOKIE_EXPIRE, "/");
	if ($_GET['zoom'] <> '') {
		$zoom = $_GET['zoom'];
	} else {
		$zoom = GOOGLE_MAPS_EARTH_ZOOM;
	}
	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">
<title>Google Maps</title>
<style>
body, div, img, ul, ol, li, p, th, td, form, pre, dl, dt, dd, fieldset, blockquote, caption, h1, h2, h3, h4, h5, h6 {
	margin: 0;
	padding: 0;
}
body {margin: 10px; }
input, select, textarea { margin: 0; }
img { border: 0; }
body {
	background-color: #ffffff;
	text-align: left;
	font-family: "MS PGothic","Osaka",Arial,sans-serif;
}
body, input, button, textarea {
	font-size: 12px;
	line-height: 1.2;
}
button, input[type="button"], input[type="submit"], input[type="reset"] {
	overflow: visible;
	margin: 1px 0;
	padding: 1px 3px;
	padding: 0 2px\9;	/* IE8以下 */
}
body:not(:target) {
	padding: 0 2px\9;	/* IE9 */
}
html {
	width: 100%;
	height: 100%;
	overflow: hidden;
}
body {
	margin: 0;
	width: 100%;
	height: 100%;
}
#form {
	margin: 5px 0 0 5px;
}
#map_canvas {
	width: 100%;
	height: 100%;
}
#panorama {
	position: absolute; bottom: 5px; right: 6px; width: 48%; height: 45%;
	border: 1px solid #666; padding: 0px; line-height: 1.4; overflow: hidden;
	background: #ffffff;
}
#panowin {
	position: relative; width: 100%; height: 100%;
	border-top: 1px solid #666; padding: 0px;
}
#route_navi {
	position: absolute;
	top: 30px; left: 0px; width: 200px; height: 90%;
	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);
}
a { color: blue; }
@media print {
	#form { display: none; }
	#side_bar { display: none; }
	#route_navi { display: none; }
	#map_canvas { position: absolute; top: 0px; left: 0px; }
}
</style>
<script src="http://maps.google.com/maps/api/js?sensor=false&libraries=panoramio,geometry"></script>
<script src="../scripts/jquery.js"></script>
<script src="../scripts/jquery.cookie.js"></script>
<script src="../scripts/encodeURL.js"></script>
<script>
var geocoder = null;
var map;
var ge;
var streetviewWin = false;
var streetviewInit = false;
var panoramioView = false;
var panoramio;
var LinePathUse = false;
var latLngWin;
function initialize() {
//	setHeightPercent('map_canvas', <?= MAPS_FIX_HEIGHT ?>);
	geocoder = new google.maps.Geocoder();
	var myOptions = {
		zoom: <?= $zoom ?>,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		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);
	showAddress('<?= $addr ?>', '<?= $_GET['photo'] ?>');
}
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;&nbsp;';
			html += '<a href="javascript:addMarker(\''+address+'\','+lat+','+lng+')">マーカー作成</a><br><br>';
			html += '標高：' + elevation + 'm<br><br>';
			latLngWin.setContent(html);
			latLngWin.setPosition(latlng);
			latLngWin.open(map);
		});
	 });
}
function showAddress(address, photo) {
	$.cookie('google_maps_address',address,{ expires: 365 });
	if (geocoder) {
		geocoder.geocode( { 'address': address}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				var position = results[0].geometry.location;
				map.setCenter(position);
				showMarker(map, position, address, photo);
					zoomMarkerAll();
			} else {
				alert(address + " が見つかりません。status: " + status);
			}
		});
	}
}
var markers = [];
var markerCnt = 0;
var current_infowin = null;
function showMarker(map, position, address, photo) {
	var icon = null;
	var html = address + '<br><br>';
	html += '緯度：' + position.lat() + '<br>';
	html += '経度：' + position.lng() + '<br><br>';
	html += '<a href="http://maps.google.com/maps?q=' + encodeURL(address);
	html += '" target="_blank">Googleマップ ≪' + address + '≫</a><br><br>';
	html += '<a href="javascript:deleteMarker('+(markerCnt+1)+')">マーカー削除</a>';
	if (photo != '') {
		html += '<br><br><a href="'+photo+'" target="_blank"><img src="'+photo+'" height=64></a>';
		icon = new google.maps.MarkerImage(
			photo,
			new google.maps.Size(<?= MAPS_PHOTO_ICON_MARKER_SIZE ?>),	// size
			new google.maps.Point(0,0),	// origin
			new google.maps.Point(16,16),	// anchor
			new google.maps.Size(<?= MAPS_PHOTO_ICON_MARKER_SIZE ?>)	// scaledSize
		);
	}
	var infowindow = new google.maps.InfoWindow({
		content: html
	});
	var marker = new google.maps.Marker({
		icon: icon,
		map: map,
		position: position
	});
	google.maps.event.addListener(marker, 'click', function() {
		if (current_infowin) {
			current_infowin.close();
		}
		infowindow.open(map,marker);
		current_infowin = infowindow;
	});
	markerCnt++;
	markers[markerCnt] = marker;
}
function clearMarker() {
	for (ix=1; ix<=markerCnt; ix++) {
		markers[ix].setMap(null);
	}
	markerCnt = 0;
}
function setHeightPercent(elementID, fixHeight) {
	// マップの高さ設定
	//if (document.all) {	// IE
	//	fixHeight += 50;
	//}
	mapsWinHeight = 100 - Math.ceil( fixHeight * 100 / screen.availHeight );
	document.getElementById(elementID).style.height = mapsWinHeight + "%";
}
function addressClear() {
	document.getElementById("address").value = '';
}
function StreetViewOnOff() {
	if (!streetviewWin) {
		StreetViewOn();
	} else {
		StreetViewOff();
	}
}
function StreetViewOn() {
	$("#panorama").css("display","");
	if (!streetviewInit) {
		var panoramaOptions = {
			pov: {
				heading: 34,
				pitch: 10,
				zoom: 1
			}
		};
		var panorama = new google.maps.StreetViewPanorama(document.getElementById("panowin"), panoramaOptions);
		map.setStreetView(panorama);
	}
	streetviewInit = true;
	streetviewWin = true;
}
function StreetViewOff() {
	$("#panorama").css("display","none");
	streetviewWin = false;
	$("#cb_sv").attr("checked", false);
}
function PanoramioOnOff(my) {
	if (my.checked) {
		panoramio.setMap(map);
	} else {
		panoramio.setMap(null);
	}
}
function getTaggedPhotos() {
	var tagFilter = document.getElementById('tag').value;
	panoramio.setTag(tagFilter);
}
function resetTaggedPhotos() {
	document.getElementById('tag').value = '';
	panoramio.setTag('');
}
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 = "";
}
function num_format(num, col) {
	if (col) {	// 小数点以下表示桁数
		multiple = 1;
		for (ix=1;ix<=col;ix++) {
			multiple *= 10;
		}
		num = Math.round(num * multiple) / multiple;
	} else {
		num = Math.round(num);
	}
	var str = new String(num).replace(/,/g/"");
	while(str != (str = str.replace(/^(-?\d+)(\d{3})/,"$1,$2")));
	return str;
}
function addMarker(addr, lat, lng) {
	var position = new google.maps.LatLng(lat, lng);
	showMarker(map, position, addr.replace('日本,',''), '');
}
function deleteMarker(markerNo) {
	markers[markerNo].setMap(null);
	delete markers[markerNo];
}
function zoomMarkerAll() {
	if (markerCnt == 0) return;
	maxLat = -999;
	minLat = 999;
	maxLng = -999;
	minLng = 999;
	for (ix=1; ix<=markerCnt; ix++) {
		if (markers[ix] != null) {
			var latlng = markers[ix].position;
			var lat = latlng.lat();
			var lng = latlng.lng();
			if (maxLat < lat) maxLat = lat;
			if (minLat > lat) minLat = lat;
			if (maxLng < lng) maxLng = lng;
			if (minLng > lng) minLng = lng;
		}
	}
	southWest = new google.maps.LatLng(minLat,minLng);
	northEast = new google.maps.LatLng(maxLat,maxLng);
	bounds = new google.maps.LatLngBounds(southWest,northEast);
	map.fitBounds(bounds);
	if (map.getZoom() > 16) {
		map.setZoom(16);
	}
	$("#c_mapCenterLat").val(map.getCenter().lat());
	$("#c_mapCenterLng").val(map.getCenter().lng());
	$("#c_mapZoomLevel").val(map.getZoom());
}
var directionsService = new google.maps.DirectionsService();
var proute = null;
var coordinates = [];
var directions;
function travelModeSelect() {
	if (proute != null) {
		plotRouteClear();
		plotRouteView();
	}
}
function plotRouteOnOff() {
	if (proute == null) {
		proute = plotRouteView();
	} else {
		plotRouteClear();
		proute = null;
	}
}
var route_navi = false;
function plotRouteView() {
	var waypoints = [];
	var start = null
	var end = null
	for (ix=1; ix<=markerCnt; ix++) {
		if (markers[ix] != null) {
			var latlng = markers[ix].position;
			waypoints.push({
				location:latlng,
				stopover:true
			});
			if (start == null) {
				start = latlng;
			} else {
				end = latlng;
			}
		}
	}
	if (end == null) {
		$("#cb_pr").attr('checked', false);
		return null;
	}
	if (route_navi) {
		directionsDisplay.setMap(null);
		directionsDisplay.setPanel(null);
	}
	directionsDisplay = new google.maps.DirectionsRenderer();
	directionsDisplay.setMap(map);
	route_navi = true;
	directionsDisplay.setPanel(document.getElementById("route_navi"));
//	$("#map_canvas").css("margin-left","220px");
// //	width = (screen.availWidth - 220) * 100 / screen.availWidth;
// //	$("#map_canvas").css("width",width+"%");
	$("#route_navi").css("display","");
	if ($("#travel_mode").val() == "w") {
		var travelMode = google.maps.DirectionsTravelMode.WALKING;
	} else {
		var travelMode = google.maps.DirectionsTravelMode.DRIVING;
	}
	var request = {
		origin: start,
		destination: end,
		waypoints: waypoints,
		optimizeWaypoints: true,
		travelMode: travelMode
	};
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.setDirections(response);
		}
	});
	return 'on';
}
function plotRouteClear() {
//	$("#map_canvas").css("margin-left","0px");
//	$("#map_canvas").css("width","100%");
	$("#route_navi").css("display","none");
	directionsDisplay.setMap(null);
}
</script>
</head>
<body onload="initialize()">
<form id="form" method="POST" action="<?= $_SERVER['SCRIPT_NAME'] ?>">
	<input id="address" class="text" type="text" style="width:160px;" name="address" value="<?= $addr ?>">
	<button onclick="showAddress(form.address.value,''); return false">検索</button><button onclick="addressClear(); return false">クリア</button><button onclick="clearMarker(); return false">マーカー削除</button><button onclick="zoomMarkerAll(); return false">マーカー全て</button>
	<label><input id="cb_path" type="checkbox" value="on" onclick="LinePathOnOff()" style="margin-left:3px;">距離：</label><input type="text" id="lineLength" style="width:60px;">m<input onclick="clearLinePath();" type="button" value="クリア">
	<label><input id="cb_pr" type="checkbox" value="on" onclick="plotRouteOnOff()" style="margin-left:3px;">ルート表示</label>
	<select id="travel_mode" onChange="travelModeSelect()">
		<option value="d">車
		<option value="w">徒歩
	</select>
	<label><input id="cb_sv" type="checkbox" value="on" onclick="StreetViewOnOff()" style="margin-left:3px;">ストリートビュー</label>
	<label><input type="checkbox" value="on" onclick="PanoramioOnOff(this)" style="margin-left:3px;">写真</label><input id="tag" type="textbox" value="" style="width:60px;">
	<input type="button" value="タグ絞込" onclick="getTaggedPhotos()"><input type="button" value="リセット" onclick="resetTaggedPhotos()">
</form>
<div id="map_canvas"></div>
<div id="route_navi" style="display:none;"></div>
<div id="panorama" style="display:none;">
人形マークを、道路上にドラッグ＆ドロップしてください。
<a href="javascript:StreetViewOff()">閉じる</a><br>
<div id="panowin"></div></div>
</body>
</html>
