<?php
	require("../__common__/__define_common.php");
	if (!defined("GETLATLNG_SLEEP_TIME")) {
		define("GETLATLNG_SLEEP_TIME", 200000);	// 0.2秒
	}
	if (!defined("MAPS_FIX_HEIGHT")) {
		define("MAPS_FIX_HEIGHT", 50);
	}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="ja">
<head>
<meta http-equiv="Content-Language" content="ja">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="author" content="ok.2nd">
<script language="javascript" src="../scripts/encodeURL.js" type="text/javascript"></script>
<title>Google Maps (複数地点)</title>
<style type="text/css">
/* * {margin: 0px; padding: 0px; } */
/*	↓ input 除く */
body, div, img, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form, fieldset, textarea, p, blockquote, th, td, caption {
	margin: 0; 
	padding: 0;
}
input {
	margin: 0;
	padding: 0 3px;
	*padding: 0;
}
input[type="submit"] {
	background-color: #e0e0e0;
}
input[type="reset"] {
	background-color: #e0e0e0;
}
input[type="button"] {
	background-color: #e0e0e0;
}
button {
	background-color: #e0e0e0;
	margin: 0;
	padding: 0 3px;
	*padding: 0;
}
textarea,input,button {
	font-family: "ＭＳ Ｐゴシック",arial,helvetica,clean,sans-serif;
	line-height: 1.3;
	*line-height: 1.0;
	font-size: 100%;
}
select {
	font-family: "ＭＳ Ｐゴシック",arial,helvetica,clean,sans-serif;
	line-height: 1.3;
	*line-height: 1.0;
	font-size: 100%;
}
textarea {
	padding: 2px;
	_padding: 0px;
	/padding: 0px;
}
html {
	width: 100%;
	height: 100%;
	overflow: hidden;
}
body {
	margin: 0;
	width: 100%;
	height: 100%;
	font-size: 84%;
}
#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: 60px; right: 6px; width: 90px; height: 60%;
	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;
}
#side_bar li {
	white-space: nowrap;
}
#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;
}
input.text {
	margin: 0px;
	padding: 1px 0 1px 0;
}
a { color: blue; }
.error_msg { color: red; margin: 20px; padding: 0; }
.noramal_msg { color: #000000; margin: 20px; padding: 0; }
</style>
</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)
?>
<div id="map_canvas"></div>
<div>Not found: <span id="not_found" style="color: red;"></span></div>
<div>Installed Plugin Version: <span id="installed-plugin-version" style="font-weight: bold;">Loading...</span></div>
<?php
}
?>
<?php
// -----------------------------------------------------
function init_body() {
?>
<body>
<?php
	form_div('');
}
?>
<?php
// -----------------------------------------------------
function form_div($addresses) {
?>
<div>
<script type="text/javascript">
function addressClear() {
	document.getElementById("address").value = '';
}
</script>
<form id="form" method="POST" action="<?= $_SERVER['SCRIPT_NAME'] ?>">
	<input id="address" class="text" type="text" size="80" name="address" value="<?= $addresses ?>">
	<input type="submit" value="地図を検索" style="background-color: #e0e0e0;">
	<button onclick="addressClear(); return false" style="margin-left:2px;">クリア</button>
	<button onclick="zoomMarkerAll(); return false" style="margin-left:0px;">マーカー全て表示</button>
<?php	if ($addresses <> '') { ?>
	<select id="travel_mode" onChange="travelModeSelect()">
		<option value="d">車
		<option value="w">徒歩
	</select>
	<input id="cb_pr" type="checkbox" value="on" onclick="plotRouteOnOff()">ルート表示
	<input id="cb_sv" type="checkbox" value="on" onclick="StreetViewOnOff()">ストリートビュー
<?php } ?>
</form>
</div>
<?php
}
// -----------------------------------------------------
function google_maps($addresses) {
?>
<script type="text/javascript" src="../scripts/jquery.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var geocoder = null;
var maxLat=-999, minLat=999, maxLng=-999, minLng=999;
var notFound = '';
var current_infowin = null;
var gmarkers = [];
var markerCnt = 0;
var side_bar_html = "";
function setHeightPercent(elementID, fixHeight) {
	// マップの高さ設定
	if (document.all) {	// IE
		fixHeight += 40;
	}
	mapsWinHeight = 100 - Math.ceil( fixHeight * 100 / screen.availHeight );
	document.getElementById(elementID).style.height = mapsWinHeight + "%";
}
function initialize() {
	setHeightPercent('map_canvas', <?= MAPS_FIX_HEIGHT ?>);
	geocoder = new google.maps.Geocoder();
	var myOptions = {
		zoom: 15,
		center: new google.maps.LatLng(35.6813820, 139.7660840),
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		disableDoubleClickZoom: false,
		streetViewControl: true
	}
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	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);
	}
?>
	showMarker(vpoint, <?= $adr_cnt ?>);
}
function showMarker(vpoint, cnt) {
	if (geocoder) {
		for (var ix=0; ix<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;
				createMarker(vpoint[ix]["address"], lat, lng);
			} else {
				notFound += vpoint[ix]["address"] + '&nbsp;';
			}
		}
		southWest = new google.maps.LatLng(minLat,minLng);
		northEast = new google.maps.LatLng(maxLat,maxLng);
		bounds = new google.maps.LatLngBounds(southWest,northEast);
		map.fitBounds(bounds);
		document.getElementById('side_bar').innerHTML = "<ul>"+side_bar_html+"</ul>";
		document.getElementById('not_found').innerHTML = notFound;
	}
}
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>';
	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
	});
	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 + ')">' + addr + '</a></li>';
	markerCnt++;
}
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%");
}
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","");
	var waypoints = [];
	for (ix=0; ix<markerCnt; ix++) {
		if (gmarkers[ix] != null) {
			var latlng = gmarkers[ix].position;
			waypoints.push({
				location:latlng,
				stopover:true
			});
		}
		if (ix == 0) {
			var start = latlng;
		} else if (ix+1 == markerCnt) {
			var 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");
	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);
	$("#c_mapCenterLat").val(map.getCenter().lat());
	$("#c_mapCenterLng").val(map.getCenter().lng());
	$("#c_mapZoomLevel").val(map.getZoom());
}
</script>
<div id="map_canvas"></div>
<div id="side_bar">Loading...</div>
<div id="route_navi" style="display:none;"></div>
<div>Not found: <span id="not_found" style="color: red;"></span></div>
<div id="panorama" style="display:none;">
人形マークを、道路上にドラッグ＆ドロップしてください。
<a href="javascript:StreetViewOff()">閉じる</a><br>
<div id="panowin"></div></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';
}
function my_file_get_contents($url) {
	static $me_called = False;
	static $proxy_context;
	if (!$me_called) {
		if (HTTP_PROXY_HOST.'' <> '') {
			$proxy = array(
				'http' => array(
					'proxy' => 'tcp://'.HTTP_PROXY_HOST.':'.HTTP_PROXY_PORT,
					'request_fulluri' => true,
				),
			);
			$proxy_context = stream_context_create($proxy);
		} else	{
			$proxy_context = False;
		}
	}
	$me_called = True;
	// httpsはエラーになる
	if ($proxy_context) {
		$html = @file_get_contents($url, False, $proxy_context);
	} else {
		$html = @file_get_contents($url);
	}
	return $html;
}
?>
