<?php
	require("../__common__/__define_common.php");
	require("../__common__/include-common-all.php");
	if (!defined("GETLATLNG_SLEEP_TIME")) {
		define("GETLATLNG_SLEEP_TIME", 200000);	// 0.2秒
	}
	if (!defined("MAPS_FIX_HEIGHT")) {
		define("MAPS_FIX_HEIGHT", 50);
	}
	if (!defined("MAPS_SIDE_BAR_WIDTH")) {
		define("MAPS_SIDE_BAR_WIDTH", "90px");
	}
	if (!defined("MAPS_PANORAMIO_TAGGEDPHOTOS")) {
		define("MAPS_PANORAMIO_TAGGEDPHOTOS", "NO");
	}
	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">
<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;
}
#side_bar {
	position: absolute; top: 80px; right: 6px; width: <?= MAPS_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;
}
#route_navi {
	position: absolute;
	top: 30px; left: 0px; width: 200px; height: 95%;
	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);
}
#route_navi_open {
	position: absolute;
	top: 30px; left: 0px; width: 14px; height: 16px;
	border: 1px solid #666; padding: 6px; line-height: 1.4; overflow:hidden;
	background: url(../images/trans-white.png);
}
a { color: blue; }
.error_msg { color: red; margin: 20px; padding: 0; }
.noramal_msg { color: #000000; margin: 20px; padding: 0; }
@media print {
	#form { display: none; }
	#side_bar { display: none; }
/*	#route_navi { display: none; }	*/
	#route_navi { top: 0px; left: 0px; width: 200px; height: 95%; }
	#route_navi_open { display: none; }
	#route_navi_close { 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>
<?php
	if ($_POST) {
		$addresses = $_POST['address'];
	} elseif (isset($_GET['addr'])) {
		$addresses = $_GET['addr'];
	}
	$addresses = str_replace('+', ' ', $addresses);
	$addresses = str_replace('　', ' ',  $addresses);
	$addresses = trim($addresses);
	if ($addresses <> '') {
		maps_body($addresses);
	} else {
		init_body();
	}
?>
</body>
</html>
<?php
// -----------------------------------------------------
function maps_body($addresses) {
?>
<body onload="initialize()">
<?php
	form_div($addresses);
	google_maps($addresses)
?>
<?php
}
?>
<?php
// -----------------------------------------------------
function init_body() {
?>
<body>
<?php
	form_div('');
}
?>
<?php
// -----------------------------------------------------
function form_div($addresses) {
?>
<div>
<script>
function addressClear() {
	document.getElementById("address").value = '';
}
</script>
<form id="form" method="POST" action="<?= $_SERVER['SCRIPT_NAME'] ?>">
	<input id="address" class="text" type="text" name="address" value="<?= $addresses ?>" style="width:300px;">
	<input type="submit" value="検索">
	<button onclick="addressClear(); return false">クリア</button>
<?php	if ($addresses <> '') { ?>
	<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:70px;">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>
<?php		if (MAPS_PANORAMIO_TAGGEDPHOTOS <> "NO") { ?>
	<input id="tag" type="textbox" value="" style="width:100px;">
	<input type="button" value="写真をタグで絞り込む" onclick="getTaggedPhotos()">
	<input type="button" value="リセット" onclick="resetTaggedPhotos()">
<?php		} ?>
<?php } ?>
</form>
</div>
<?php
}
// -----------------------------------------------------
function google_maps($addresses) {
?>
<script src="../scripts/jquery.js"></script>
<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;
var gmarkers = [];
var addrPool = [];
var markerCnt = 0;
var side_bar_html = "";
var panoramioView = false;
var panoramio;
var LinePathUse = false;
var latLngWin;
function setHeightPercent(elementID, fixHeight) {
	// マップの高さ設定
	//if (document.all) {	// IE
	//	fixHeight += 40;
	//}
	mapsWinHeight = 100 - Math.ceil( fixHeight * 100 / screen.availHeight );
	document.getElementById(elementID).style.height = mapsWinHeight + "%";
}
<?php
	if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
		$width_sub = 560;
	} else {
		$width_sub = 500;
	}
?>
function winResize() {
	if (document.body.clientWidth < 1000) {
		if ((width = document.body.clientWidth - <?= $width_sub ?>) < 80) {
			width = 80;
		}
		$("#address").css("width",width);
	}
}
function initialize() {
//	setHeightPercent('map_canvas', <?= MAPS_FIX_HEIGHT ?>);
	maxLat = -999;
	minLat = 999;
	maxLng = -999;
	minLng = 999;
	var vpoint = Array();
<?php
	$ary = explode(" ", $addresses);
	$adr_cnt = 0;
	foreach ($ary as $address) {
		$status = getLatLng($address, $lat, $lng);
?>
	vpoint[<?= $adr_cnt ?>] = Array();
	vpoint[<?= $adr_cnt ?>]["address"] = '<?= $address ?>';
	vpoint[<?= $adr_cnt ?>]["lat"] = <?= $lat ?>;
	vpoint[<?= $adr_cnt ?>]["lng"] = <?= $lng ?>;
	vpoint[<?= $adr_cnt ?>]["status"] = '<?= $status ?>';
<?php
		++$adr_cnt;
	//	usleep(GETLATLNG_SLEEP_TIME);
	}
?>
	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);
	map.fitBounds(bounds);
	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);
	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;&nbsp;';
			html += '<a href="javascript:addMarker(\''+address+'\','+lat+','+lng+')">マーカー作成</a><br><br>';
			html += '標高：' + elevation + 'm';
			latLngWin.setContent(html);
			latLngWin.setPosition(latlng);
			latLngWin.open(map);
		});
	 });
}
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"], lat, lng);
		} else {
			notFound += vpoint[ix]["address"] + '&nbsp;';
		}
	}
	document.getElementById('side_bar').innerHTML = "<ul>"+side_bar_html+"</ul>";
	//document.getElementById('not_found').innerHTML = notFound;
}
function addMarker(addr, lat, lng) {
	createMarker(addr.replace('日本,',''), lat, lng);
	document.getElementById('side_bar').innerHTML = "<ul>"+side_bar_html+"</ul>";
	latLngWin.close(map);
}
function createMarker(addr, lat, lng) {
	html = addr + '<br><br>';
	html += '緯度：' + lat + '<br>';
	html += '経度：' + lng + '<br><br>';
	html += '<a href="http://maps.google.com/maps?q=' + encodeURL(addr);
	html += '" target="_blank">Googleマップ ≪' + addr + '≫</a><br><br>';
	html += '<a href="javascript:deleteMarker('+markerCnt+')">マーカー削除</a>';
	var infowindow = new google.maps.InfoWindow({
		content: html
	});
	var latlng = new google.maps.LatLng(lat, lng);
/*
	var marker = new google.maps.Marker({
		position: latlng,
		map: map,
		title: addr
	});
*/
	var marker_label = zen2han(addr).replace(/&/g,'＆').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.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: addr,
		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;
	addrPool[markerCnt] = addr;
	side_bar_html += '<li><a href="javascript:myClick(' + markerCnt + ')">' + addr + '</a></li>';
	markerCnt++;
}
function deleteMarker(markerNo) {
	gmarkers[markerNo].setMap(null);
	delete gmarkers[markerNo];
	delete addrPool[markerNo];
	//	gmarkers.splice(markerNo, 1);
	//	addrPool.splice(markerNo, 1);
	//	markerCnt--;
	side_bar_html = ''
	for (var ix=0; ix<markerCnt; ix++) {
		if (addrPool[ix] != null) {
			side_bar_html += '<li><a href="javascript:myClick(' + ix + ')">' + addrPool[ix] + '</a></li>';
		}
	}
	document.getElementById('side_bar').innerHTML = "<ul>"+side_bar_html+"</ul>";
}
function myClick(markerCnt) {
	google.maps.event.trigger(gmarkers[markerCnt], 'click');
}
var streetviewWin = false;
var streetviewInit = false;
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;
	$("#side_bar").css("height","35%");
}
function StreetViewOff() {
	$("#panorama").css("display","none");
	streetviewWin = false;
	$("#cb_sv").attr("checked", false);
	$("#side_bar").css("height","70%");
}
function PanoramioOnOff(me) {
	if (me.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('');
}
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) {
		plotRouteView();
		proute = 'on';
	} else {
		plotRouteClear();
		proute = null;
	}
}
var route_navi = false;
function plotRouteView() {
	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","");
	$("#route_navi_open").css("display","none");
	var waypoints = [];
	var start = null
	var end = null
	for (ix=0; ix<markerCnt; ix++) {
		if (gmarkers[ix] != null) {
			var latlng = gmarkers[ix].position;
			waypoints.push({
				location:latlng,
				stopover:true
			});
			if (start == null) {
				start = latlng;
			} else {
				end = latlng;
			}
		}
	}
	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);
		}
	});
}
function plotRouteClear() {
//	$("#map_canvas").css("margin-left","0px");
//	$("#map_canvas").css("width","100%");
	$("#route_navi").css("display","none");
	$("#route_navi_open").css("display","none");
	directionsDisplay.setMap(null);
}
function zoomMarkerAll() {
	maxLat = -999;
	minLat = 999;
	maxLng = -999;
	minLng = 999;
	for (ix=0; ix<markerCnt; ix++) {
		if (gmarkers[ix] != null) {
			var latlng = gmarkers[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());
}
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="side_bar">Loading...</div>
<div id="route_navi" style="display:none;">
<div id="route_navi_close"><a href="javascript:route_naviOff()">×</a> <a href="javascript:route_naviOff()">ルートナビを閉じる</a><br></div>
</div>
<div id="route_navi_open" style="display:none;"><a href="javascript:route_naviOn()">▽</a></div>
<div id="panorama" style="display:none;">
人形マークを、道路上にドラッグ＆ドロップしてください。
<a href="javascript:StreetViewOff()">閉じる</a><br>
<div id="panowin"></div></div>
<script>
function route_naviOff() {
	$("#route_navi").css("display","none");
	$("#route_navi_open").css("display","");
}
function route_naviOn() {
	$("#route_navi_open").css("display","none");
	$("#route_navi").css("display","");
}
</script>
<?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';
}
?>
