<?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);
	}
	if (!defined("GOOGLE_MAPS_PLACE_TYPES")) {
		define("GOOGLE_MAPS_PLACE_TYPES", "google_maps_place_types.php");
	}
	if (!defined("GOOGLE_MAPS_PLACE_ICON")) {
		define("GOOGLE_MAPS_PLACE_ICON", DIARY_MAPS_ICON_FOLDER."markerSmall80.png");
	}
?>
<!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%x;
	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,places"></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 PlacesSearch() {
	var place_type = $("#places").val();
	$.cookie('google_maps_place_type',place_type,{ expires: 365 });
	var currentBounds = map.getBounds();
	var request = {
		bounds: currentBounds,
		types: [place_type]
	};
	var service = new google.maps.places.PlacesService(map);
	if (placesMarkerCnt != 0) {
		for (ix=0; ix<placesMarkerCnt; ix++) {
			placesMarker[ix].setMap(null);
		}
		placesMarkerCnt = 0;
	}
	service.search(request, PlacesSearchCallback);
}
var placesMarker = [];
var placesMarkerCnt = 0;
function PlacesSearchCallback(results, status) {
	if (status == google.maps.places.PlacesServiceStatus.OK) {
		for (var i = 0; i < results.length; i++) {
			// createPlacesMarker(results[i]);
			PlaceGetDetails(results[i]);
		}
	}
}
function PlaceGetDetails(place) {
	var service = new google.maps.places.PlacesService(map);
	var request = { reference: place.reference };
	service.getDetails(request, GetDetailsCallback);
}
function GetDetailsCallback(place, status) {
	if (status == google.maps.places.PlacesServiceStatus.OK) {
		createPlacesMarker(place);
	}
}
function createPlacesMarker(place) {
	var placeLoc = place.geometry.location;
	newicon = '<?= GOOGLE_MAPS_PLACE_ICON ?>';
/*
		var icon_x = new google.maps.MarkerImage(newicon,
			new google.maps.Size(32, 32),
			new google.maps.Point(0, 0),
			new google.maps.Point(16, 32));
		var placesMarker_x = new google.maps.Marker({
			map: map,
			icon: icon_x,
			title: place.name,
			position: new google.maps.LatLng(placeLoc.lat(), placeLoc.lng())
		});
*/
	var marker_label = zen2han(place.name).slice(0, 10);
	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.size = new google.maps.Size(32, 32);
	//	icon_s.origin = new google.maps.Point(0, 0);
	icon_s.anchor = new google.maps.Point(8, 36);
	icon_s.scaledSize = new google.maps.Size(str_width(marker_label)*5+20, 28);
	placesMarker[placesMarkerCnt] = new google.maps.Marker({
		map: map,
		icon: icon_s,
		title: place.name,
		position: new google.maps.LatLng(placeLoc.lat(), placeLoc.lng())
	});
	//	position: new google.maps.LatLng(placeLoc.lat()+0.0001, placeLoc.lng()+0.0008)
	var infowindow = new google.maps.InfoWindow();
	var html = '<a href="http://www.google.com/search?q=' + place.name + '" target="_blank" style="color:#0000c0;font-weight:bold;">' + place.name + '</a><br>';
	html += place.formatted_phone_number + '<br><br>';
	html += '<a href="http://maps.google.com/maps?q=' + place.geometry.location.lat() + ',' + place.geometry.location.lng();
	html += '" target="_blank">Googleマップ</a><br><br>';
	html += '<a href="javascript:deletePlacesMarker('+(placesMarkerCnt)+')">マーカー削除</a>';
	google.maps.event.addListener(placesMarker[placesMarkerCnt], 'click', function() {
		infowindow.setContent(html);
		infowindow.open(map, this);
	});
	placesMarkerCnt++;
}
function deletePlacesMarker(markerNo) {
	placesMarker[markerNo].setMap(null);
	delete placesMarker[markerNo];
}
function clearPlacesMarker() {
	for (ix=0; ix<placesMarkerCnt; ix++) {
		placesMarker[ix].setMap(null);
	}
	placesMarkerCnt = 0;
}
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)+')">マーカー削除</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;
	});
	markers[markerCnt] = marker;
	markerCnt++;
}
function clearMarker() {
	for (ix=0; 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_opt").css("display","");
		panoramio.setMap(map);
	} else {
		$("#panoramio_opt").css("display","none");
		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=0; 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=0; 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);
}
function str_width(str) {
// 文字列の文字幅(漢字は2)を求める。
	var r = 0;
	for (var i = 0; i < str.length; i++) {
		var c = str.charCodeAt(i);
		// Shift_JIS: 0x0 ～ 0x80, 0xa0 , 0xa1 ～ 0xdf , 0xfd ～ 0xff
		// Unicode : 0x0 ～ 0x80, 0xf8f0, 0xff61 ～ 0xff9f, 0xf8f1 ～ 0xf8f3
		if ((c >= 0x0 && c < 0x81) || (c == 0xf8f0) || (c >= 0xff61 && c < 0xffa0) || (c >= 0xf8f1 && c < 0xf8f4)) {
			r += 1;
		} else {
			r += 2;
		}
	}
	return r;
}
function zen2han(text) {
// 全角を半角にする
	var i, charCode, charArray = [];
	for(i=text.length-1;0<=i;i--) {
		charCode = charArray[i] = text.charCodeAt(i);
		switch(true) {
			case (charCode <= 0xff5e && 0xff01 <= charCode):
				charArray[i] -= 0xfee0;
				break;
			case (charCode == 0x3000):
				charArray[i] = 0x0020;
				break;
			case (charCode == 0x30FC):
				charArray[i] = 0x002D;
				break;
		}
	}
	return String.fromCharCode.apply(null, charArray);
}
</script>
</head>
<?php
	if ($_COOKIE['google_maps_place_type'] <> '') {
		$place_type = $_COOKIE['google_maps_place_type'];
	} else {
		$place_type = '';
	}
	require(GOOGLE_MAPS_PLACE_TYPES);
?>
<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:50px;">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><select id="places">
<?php
	$pre_place = '';
	foreach ($place_tbl as $place) {
		if ($place[0] <> $pre_place) {
?>
		<optgroup label="<?= $place[0] ?>">
<?php
		}
		$pre_place = $place[0];
?>
		<option value="<?= $place[1] ?>"<?= ($place_type == $place[1]) ? ' selected' : '' ?>><?= $place[2] ?></option>
<?php
	}
?>
	</select><button onclick="PlacesSearch();return false;">探す</button><button onclick="clearPlacesMarker();return false;">ｸﾘｱ</button>
	<label><input type="checkbox" value="on" onclick="PanoramioOnOff(this)" style="margin-left:3px;">写真</label><span id="panoramio_opt" style="display: none;"><input id="tag" type="textbox" value="" style="width:60px;">
	<input type="button" value="タグ絞込" onclick="getTaggedPhotos()"><input type="button" value="リセット" onclick="resetTaggedPhotos()"></span>
</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>
