目次
サンプル・プログラムの実行例
サンプル・プログラム
viewChronologic.php | サンプル・プログラム本体 |
chronologic.xml | 年表ファイル |
SVGとは何か
公開当初はサポートしているブラウザが少なく、描画にはアドインが必要だったりしたことから普及が進まなかったが、HTML5ブラウザがサポートしたことからブレイク。アニメーション機能も備えていることから、Flashコンテンツの代替もできる。
ベクター描画であることから、画像を拡大縮小してもジャギーがあらわれないことが大きなメリットである。また、テキストの配置座標も細かく指定できるので、ブラウザによって表やグラフのレイアウトが崩れるという心配もない。
今回は利用していないが、レイヤー機能も備えている。
ぱふぅ家のホームページでは、年表のほか、当コーナーで表示しているXMLデータ構造やフローチャートをSVGを使って描画している。
準備
0034: //年表ファイル
0035: define('FILE_CHRONOLOGIC', 'chronologic.xml');
0036:
0037: //年表(幅)
0038: define('CHRONOLOGIC_WIDTH', 600);
0039:
0040: //インデント:左側
0041: define('CHRONOLOGIC_LEFT', 30);
0042:
0043: //イベントの高さ
0044: define('CHRONOLOGIC_EVENT_HEIGHT', 34);
0045:
0046: //年表地図(幅)
0047: define('CHRONOLOGICMAP_WIDTH', 600);
0048:
0049: //年表地図(高さ)
0050: define('CHRONOLOGICMAP_HEIGHT', 350);
0051:
0052: //ぱふぅ家のホームページ家のリンク・パス
0053: define('URL_PAHOO', 'https://www.pahoo.org/culture/numbers/year/');
0054:
0055: //Googleマップ用マーカー・ファイルのパス;png限定
0056: define('PATH_MARKER', 'https://www.pahoo.org/common/marker/');
0057:
0058: //Goole APIキー;各自の環境に合わせてください
0059: define('GOOGLE_API_KEY', '*******************************************');
0060:
0061: //GoogleMapsの数
0062: $CountGoogleMaps = 1;
0063:
0064: /**
0065: * 表示フォントファミリー
0066: * @global double $ChronoFont
0067: */
0068: $ChronoFont = 'sans-serif';
0069:
0070: /**
0071: * ピクセル/年
0072: * @global double $ChronoPixelYear
0073: */
0074: $ChronoPixelYear = 0.0;
0075:
0076: /**
0077: * 開始年
0078: * @global int $ChronoStart
0079: */
0080: $ChronoStart = 0;
この他、年表の幅や、表示フォント・ファミリーなど、各種の初期設定を定数に記述している。
XMLファイルに記述したリンク先ファイルは、定数 URL_PAHOO にあることを想定している。適宜書き換えていただきたい。
また、Googleマップに立てるマーカーは、定数 PATH_MARKER にあることを想定している。こちらも必要に応じて書き換えていただきたい。
Googleマップを利用するために Google Cloud Platform APIキー が必要で、その入手方法は「Google Cloud Platform - WebAPIの登録方法」を参照されたい。
解説:XMLファイル
解説:配列へ格納
0174: /**
0175: * 年表:XMLデータを配列へ格納
0176: * @param object $xml 年表:XMLデータ
0177: * @param array $items 格納する配列
0178: * @return int 格納件数
0179: */
0180: function xml2array($xml, &$items) {
0181: $cnt = 0;
0182: foreach ($xml->record as $elm) {
0183: $items[$cnt]['caption'] = '';
0184: $items[$cnt]['label'] = '';
0185: $items[$cnt]['event'] = '';
0186: $items[$cnt]['caption'] =
0187: isset($elm->caption) ? (string)$elm->caption : '';
0188: $items[$cnt]['description'] =
0189: isset($elm->description) ? (string)$elm->description : '';
0190: if (isset($elm->label)) $ss = (string)$elm->label;
0191: else if (isset($elm->event)) $ss = (string)$elm->event;
0192: else if (isset($elm->name)) $ss = (string)$elm->name;
0193: $items[$cnt]['label'] = isset($ss) ? $ss : '';
0194: $items[$cnt]['start'] = isset($elm->start) ? (string)$elm->start : '';
0195: $items[$cnt]['finish'] = isset($elm->finish) ? (string)$elm->finish : '';
0196: $items[$cnt]['filename'] = isset($elm->filename) ? (string)$elm->filename : '';
0197: $items[$cnt]['latitude'] = isset($elm->latitude) ? (double)$elm->latitude : '';
0198: $items[$cnt]['longitude'] = isset($elm->longitude) ? (double)$elm->longitude : '';
0199: $items[$cnt]['icon'] = isset($elm->icon) ? (string)$elm->icon : '';
0200: $cnt++;
0201: }
0202:
0203: return $cnt;
0204: }
解説:1つのイベントを作成
0372: /**
0373: * 1つのイベントを作成する
0374: * @param array $item 年代記の要素
0375: * @param int $y Y座標
0376: * @return string SVG文字列
0377: */
0378: function mkchronologic_sub($item, $y, $id) {
0379: global $ChronoPixelYear, $ChronoStart, $ChronoFont;
0380:
0381: $font_size = 12; //描画テキストのフォント・サイズ
0382: $start = __chronoyear($item['start']);
0383: $finish = __chronoyear($item['finish']);
0384:
0385: //$x1:バーの左端X座表 $width:バーの幅
0386: //$x2:開始年のX座標 $x3:終了年のX座標
0387: $x1 = (int)(CHRONOLOGIC_LEFT + ($start - $ChronoStart) * $ChronoPixelYear);
0388: if ($start == $finish) {
0389: $width = 5;
0390: $item['start'] = '';
0391: $x1 -= 5;
0392: $x2 = $x1 + 5;
0393: } else {
0394: $width = (int)(($finish - $start) * $ChronoPixelYear);
0395: $x2 = $x1 - 5;
0396: }
0397: $x3 = $x1 + $width + 5;
0398:
0399: //イベントのラベル
0400: if ($item['label'] != '') $label = $item['label'];
0401: else if ($item['caption'] != '') $label = $item['caption'];
0402: else $label = '';
0403:
0404: //ラベルの配置 $x4:ラベルのX座標
0405: $len = mb_strlen($label);
0406: //バーの中
0407: if ($len * $font_size < $width) {
0408: $x4 = (int)($x1 + ($width / 2));
0409: $anchor = 'middle';
0410: //バーの左
0411: } else if ($item['start'] == '') {
0412: $x4 = $x2 - $font_size * mb_strlen($item['start']) - 10;
0413: $anchor = 'end';
0414: } else {
0415: $x4 = $x2 - $font_size * mb_strlen($item['start']);
0416: $anchor = 'end';
0417: }
0418: //バーの右
0419: if ($x4 - $len * $font_size <= 0) {
0420: $x4 = $x3 + $font_size * mb_strlen($item['finish']);
0421: $anchor = 'start';
0422: }
0423: $y1 = $y + 5;
0424: $height = CHRONOLOGIC_EVENT_HEIGHT - 10;
0425: $y2 = (int)($y1 + $height / 1.3);
0426:
0427: //ラベルとリンク
0428: if (preg_match('/\.xml/', $item['filename']) > 0) {
0429: $link = URL_PAHOO . preg_replace('/\.xml/', '.shtm', $item['filename']);
0430: $color = '#0000FF';
0431: $tooltip = 'サイト内リンク';
0432: } else if ($label != '') {
0433: $link = 'https://www.google.co.jp/search?q=' . urlencode($label);
0434: $color = '#333333';
0435: $tooltip = '外部リンク';
0436: } else {
0437: $link = '';
0438: $color = '#000000';
0439: }
0440: if ($label != '') {
0441: if ($link == '') {
0442: $link =<<< EOT
0443: <text x="{$x4}" y="{$y2}" font-family="{$ChronoFont}" font-size="{$font_size}" fill="{$color}" text-anchor="{$anchor}" >{$label}</text>
0444:
0445: EOT;
0446: } else {
0447: $link =<<< EOT
0448: <a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="{$link}">
0449: <text x="{$x4}" y="{$y2}" font-family="{$ChronoFont}" font-size="{$font_size}" fill="{$color}" text-anchor="{$anchor}" onmousemove="ShowTooltip(evt, '{$tooltip}', {$x1}, {$y1}, '')" onmouseout="HideTooltip(evt)" >{$label}</text>
0450: </a>
0451:
0452: EOT;
0453: }
0454: }
0455:
0456: //バーとツールチップ
0457: if ($item['description'] != '') $tooltip = $item['description'];
0458: else $tooltip = '';
0459: $str = sprintf('rect%04d', $id);
0460: if ($tooltip == '') {
0461: $bar =<<< EOT
0462: <rect id="{$str}" x="{$x1}" y="{$y1}" width="{$width}" height="{$height}" fill="#FFBB00" stroke="none" />
0463:
0464: EOT;
0465: } else {
0466: $bar =<<< EOT
0467: <rect id="{$str}" x="{$x1}" y="{$y1}" width="{$width}" height="{$height}" fill="#FFBB00" stroke="none" onmousemove="ShowTooltip(evt, '{$tooltip}', {$x1}, {$y1}, '{$str}')" onmouseout="HideTooltip(evt)" />
0468:
0469: EOT;
0470: }
0471:
0472: $svg =<<< EOT
0473: {$bar}
0474: <text x="{$x2}" y="{$y2}" font-family="{$ChronoFont}" font-size="{$font_size}" fill="black" text-anchor="end">{$item['start']}</text>
0475: <text x="{$x3}" y="{$y2}" font-family="{$ChronoFont}" font-size="{$font_size}" fill="black" text-anchor="start">{$item['finish']}</text>
0476: {$link}
0477:
0478: EOT;
0479:
0480: return $svg;
0481: }
まず、読み込んだデータには、たとえば生年が不明だったり、まだ存命の人物の場合には開始年/終了年が入っていない。そこで、ユーザー関数 __chronoyear を呼び出して、描画用のための仮年号を取得する。
次に、各要素の描画X座標 $x1~$x3 やバーの幅 $width や高さ $height を計算する。
バーが短いときは、ラベルはバーの左側に配置。左側に配置して表枠外にはみ出すようだったら、バーの右側に配置するように座標計算する。
次にラベルを、SVGの text要素を使って描く。text-anchor属性を併用することで、バーに対してテキストを揃えている。
また、リンク先がある場合は、a要素を使ってハイパーリンクを張っている。
バーは、SVGの rect要素を使って描く。
description情報がある場合は、ツールチップを表示するようにした。ツールチップはJavaScriptで実装しており、「How to create an SVG “tooltip”-like box?」(Stack Overflow)の回答を参考にした。
最後に開始年と終了年を、SVGの text要素を使って描く。
解説:横軸を作成
0306: /**
0307: * 横軸を作成する
0308: * @param array $items 年代記の要素
0309: * @param int $width 年代記の横幅(単位:ピクセル,200以上)
0310: * @return string SVG文字列
0311: */
0312: function mkscale($items, $width, $height) {
0313: global $ChronoPixelYear, $ChronoStart, $ChronoFont;
0314:
0315: //年の範囲
0316: $year_min = +99999;
0317: $year_max = -99999;
0318: foreach ($items as $item) {
0319: $year = __chronoyear($item['start']);
0320: if ($year < $year_min) $year_min = $year;
0321: $year = __chronoyear($item['finish']);
0322: if ($year > $year_max) $year_max = $year;
0323: }
0324:
0325: //年の範囲:丸め
0326: $table = array(
0327: array(1, 5),
0328: array(2, 10),
0329: array(5, 25),
0330: array(10, 50),
0331: array(15, 75),
0332: array(25, 125),
0333: array(50, 250),
0334: array(100, 500),
0335: array(150, 750),
0336: array(200, 1000),
0337: array(300, 1500),
0338: array(400, 2000)
0339: );
0340: $period = $year_max - $year_min + 1;
0341: foreach ($table as $arr) {
0342: $delta = ($arr[0] <= 25) ? $arr[0] : 25;
0343: if ($period <= $arr[1]) {
0344: $interval = $arr[0];
0345: $start = round($year_min / $interval) * $interval - $delta;
0346: $finish = round($year_max / $interval) * $interval + $delta;
0347: break;
0348: }
0349: }
0350: $ChronoPixelYear = ($width - 80) / ($finish - $start);
0351: $ChronoStart = $start;
0352:
0353: $svg =<<< EOT
0354: <rect x="0" y="0" width="{$width}" height="{$height}" fill="none" stroke="#FFBB00" stroke-width="3" />
0355: <rect x="0" y="0" width="{$width}" height="30" fill="#FFBB00" stroke="none" />
0356:
0357: EOT;
0358: for ($year = $start; $year <= $finish; $year += $interval) {
0359: $x1 = (int)(CHRONOLOGIC_LEFT + ($year - $start) * $ChronoPixelYear);
0360: $x2 = $x1 - 15;
0361: $y1 = 30;
0362: $y2 = $height;
0363: $svg .=<<< EOT
0364: <text x="{$x2}" y="25" font-family="{$ChronoFont}" font-size="14" fill="black" >{$year}</text>
0365: <line x1="{$x1}" y1="{$y1}" x2="{$x1}" y2="{$y2}" stroke="#FFDD88" stroke-width="1" />
0366:
0367: EOT;
0368: }
0369: return $svg;
0370: }
解説:年表を作成
0206: /**
0207: * 年表を作成する
0208: * @param array $info 年代記の要素
0209: * string $items[]['caption'] = 棒グラフ上のキャプション
0210: * string $items[]['label'] = 棒グラフ上のラベル
0211: * int $items[]['start'] = 開始年(生年)(必須)
0212: * int $items[]['finish'] = 終了年(没年)(必須)
0213: * string $items[]['filename'] = リンク先ファイル名(XML)
0214: * @return string SVG文字列
0215: */
0216: function get_chronologic($items) {
0217: $width = CHRONOLOGIC_WIDTH;
0218: $height = count($items) * CHRONOLOGIC_EVENT_HEIGHT + 80;
0219: $scale = mkscale($items, $width, $height); //横軸作成
0220: $table = mkchronologic($items, $width); //年表作成
0221:
0222: $svg =<<< EOT
0223: <!-- 年表 -->
0224: <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" onload="init(evt)" width="{$width}" height="{$height}">
0225: <style>
0226: .caption {
0227: font-size: 14px;
0228: font-family: Georgia, serif;
0229: }
0230: .tooltip {
0231: font-size: 12px;
0232: }
0233: .tooltip_bg {
0234: fill: white;
0235: stroke: black;
0236: stroke-width: 1;
0237: opacity: 0.85;
0238: }
0239: </style>
0240:
0241: <script type="text/ecmascript">
0242: <![CDATA[
0243: function init(evt) {
0244: if (window.svgDocument == null) {
0245: svgDocument = evt.target.ownerDocument;
0246: }
0247: tooltip = svgDocument.getElementById('tooltip');
0248: tooltip_bg = svgDocument.getElementById('tooltip_bg');
0249: }
0250:
0251: function ShowTooltip(evt, mouseovertext, x, y, id) {
0252: tooltip.setAttributeNS(null,"x",evt.clientX + 11);
0253: tooltip.setAttributeNS(null,"y",y + 27);
0254: tooltip.firstChild.data = mouseovertext;
0255: tooltip.setAttributeNS(null,"visibility","visible");
0256:
0257: length = tooltip.getComputedTextLength();
0258: tooltip_bg.setAttributeNS(null,"width",length + 8);
0259: tooltip_bg.setAttributeNS(null,"x",evt.clientX + 8);
0260: tooltip_bg.setAttributeNS(null,"y",y + 14);
0261: tooltip_bg.setAttributeNS(null,"visibility","visibile");
0262: }
0263:
0264: function HideTooltip(evt) {
0265: tooltip.setAttributeNS(null,"visibility","hidden");
0266: tooltip_bg.setAttributeNS(null,"visibility","hidden");
0267: }
0268: ]]>
0269: </script>
0270:
0271: {$scale}
0272: {$table}
0273:
0274: <rect class="tooltip_bg" id="tooltip_bg"
0275: x="0" y="0" rx="4" ry="4"
0276: width="55" height="17" visibility="hidden"/>
0277: <text class="tooltip" id="tooltip"
0278: x="0" y="0" visibility="hidden">Tooltip</text>
0279: </svg>
0280:
0281: EOT;
0282:
0283: return $svg;
0284: }
ユーザー関数 mkscale と mkchronologic を呼び出し年表を描画する。
また、ツールチップを表示するためのJavaScriptも記述してある。
解説:年表地図を作成
0509: /**
0510: * 年表地図を作成する
0511: * @param array $info 年代記の要素
0512: * string $items[]['caption'] = 棒グラフ上のキャプション
0513: * string $items[]['label'] = 棒グラフ上のラベル
0514: * int $items[]['start'] = 開始年(生年)(必須)
0515: * int $items[]['finish'] = 終了年(没年)(必須)
0516: * double $items[]['latitude'] = 緯度
0517: * double $items[]['longitude'] = 経度
0518: * string $items[]['icon'] = マーカー・ファイル名(拡張子は除く)
0519: * double $items[]['description'] = 記事
0520: * string $items[]['filename'] = リンク先ファイル名(XML)
0521: * @return string HTMLテキスト
0522: */
0523: function get_chronologicalmap($items) {
0524: global $CountGoogleMaps;
0525:
0526: $apikey = GOOGLE_API_KEY;
0527: $width = CHRONOLOGICMAP_WIDTH;
0528: $height = CHRONOLOGICMAP_HEIGHT;
0529: $mode = 'ROADMAP';
0530: $zoom = 1;
0531: $lat = '';
0532: $lng = '';
0533: $js = ($CountGoogleMaps > 1) ? '' :
0534: "<script type=\"text/javascript\" src=\"https://maps.google.com/maps/api/js?key={$apikey}&region=JP\"></script>";
0535:
0536: $flag = FALSE;
0537: $str = '';
0538: $arrs = array();
0539: foreach ($items as $item) {
0540: if (($item['latitude'] != '') && ($item['longitude'] != '')) {
0541: $key = $item['latitude'] .',' . $item['longitude'];
0542: if (! $flag) {
0543: //中心座標
0544: $lat = (double)$item['latitude'];
0545: $lng = (double)$item['longitude'];
0546: $flag = TRUE;
0547: }
0548: //ラベルとリンク
0549: if (preg_match('/\.xml/', $item['filename']) > 0) {
0550: $link = URL_PAHOO . preg_replace('/\.xml/', '.shtm', $item['filename']);
0551: $color = '#0000FF';
0552: $tooltip = 'サイト内リンク';
0553: } else if ($label != '') {
0554: $link = 'https://www.google.co.jp/search?q=' . urlencode($label);
0555: $color = '#333333';
0556: $tooltip = '外部リンク';
0557: } else {
0558: $link = '';
0559: $color = '#000000';
0560: }
0561: //年号
0562: $year = ($item['start'] == $item['finish']) ? $item['start']:
0563: $item['start'] . ' - ' . $item['finish'];
0564: //マーカー
0565: $marker = (isset($item['icon']) && ($item['icon'] != '')) ? PATH_MARKER . $item['icon'] .'.png' : PATH_MARKER . 'history.png';
0566: //配列へ代入
0567: $arrs[$key]['latitude'] = $item['latitude'];
0568: $arrs[$key]['longitude'] = $item['longitude'];
0569: $arrs[$key]['title'] = $item['label'];
0570: $label = ($link == '') ? "<span style=\"color:blue;\"{$item['label']}" : "<a href=\"{$link}\" target=\"_blank\">{$item['label']}</a>";
0571: $description = ($item['description'] == '') ? '' : "‥‥{$item['description']}";
0572: $content = "<p style=\"text-align:left;\">{$label} ({$year}年)<span style=\"font-size:80%;\">{$description}</span></p>";
0573: //重複イベントはスキップ
0574: if (isset($arrs[$key]['content'])) {
0575: if (mb_strstr($arrs[$key]['content'], $content) == FALSE) {
0576: $arrs[$key]['content'] .= $content;
0577: }
0578: } else {
0579: $arrs[$key]['content'] = $content;
0580: }
0581: $arrs[$key]['marker'] = $marker;
0582: }
0583: }
0584:
0585: //JavaScript生成
0586: $str = '';
0587: $n = 1;
0588: foreach ($arrs as $arr) {
0589: $str .= <<< EOT
0590: var icon_{$n} = new google.maps.MarkerImage('{$arr['marker']}');
0591: var marker_{$n} = new google.maps.Marker({
0592: position: new google.maps.LatLng({$arr['latitude']}, {$arr['longitude']}),
0593: map: map,
0594: icon: icon_{$n},
0595: title: '{$arr['title']}',
0596: zIndex: 250
0597: });
0598: var infowindow_{$n} = new google.maps.InfoWindow({
0599: content: '{$arr['content']}',
0600: size: new google.maps.Size(200, 100)
0601: });
0602: google.maps.event.addListener(marker_{$n}, 'click', function() {
0603: infowindow_{$n}.open(map, marker_{$n});
0604: });
0605:
0606: EOT;
0607: $n++;
0608: }
0609: //地図情報がない
0610: if (($lat == '') || ($lng == '')) return '';
0611:
0612: $dest =<<< EOT
0613: {$js}
0614: <script type="text/javascript">
0615: <!--
0616: google.maps.event.addDomListener(window, 'load', function() {
0617: var mapdiv = document.getElementById('gmap{$CountGoogleMaps}');
0618: var myOptions = {
0619: zoom: {$zoom},
0620: center: new google.maps.LatLng({$lat}, {$lng}),
0621: mapTypeId: google.maps.MapTypeId.{$mode},
0622: mapTypeControl: false,
0623: scaleControl: true
0624: };
0625: var map = new google.maps.Map(mapdiv, myOptions);
0626: {$str}
0627:
0628: });
0629: -->
0630: </script>
0631: <div style="margin-bottom:20px;">
0632: <div id="gmap{$CountGoogleMaps}" style="width:{$width}px; height:{$height}px;">
0633: </div>
0634: </div>
0635:
0636: EOT;
0637: $CountGoogleMaps++;
0638:
0639: return $dest;
0640: }
GooleMaps API の使い方は「PHPで地図で指定した場所の天気予報を求める」などで解説しているので、あわせてご覧いただきたい。
冒頭で、Googleマップの縦・横のサイズと、モード $mode、ズーム $zoom を指定している。
次に、引数として与えられた年表情報配列 $items を1つずつ解析していく。
地図の中心は、最初の要素の位置情報を採用する。
参考サイト
- SVG 1.1 仕様 (第2版) 日本語訳
- svg要素でベクターグラフィクスを埋め込もう:ほんっとにはじめてのHTML5とCSS3
- SVGで線、円、矩形を描画する:Symfoware
- SVGテスト用ひな形とプレビュー(基本図形):スタンダード・デザインラボ
今回は、この部分のPHPプログラムを紹介する。
2017年(平成29年)10月、世界のどこでイベントが発生したかを俯瞰できるよう、Googleマップ上にマーカーを立てる機能を追加した。
(2022年4月9日)PHP8対応,リファラ・チェック改良