javascriptで配列に追加

配列に追加はpushを使います。

var icon = [];
var list = JSON.parse('');
for (var i = 0; i < list.length; i++){
	if(list[i] =='Clear'){
	 icon.push('/img/icon05.png');
	}else if(list[i] =='Clouds'){
	 icon.push('/img/icon06.png');
	} else{
	 icon.push('/img/icon07.png');
	}
}

下記のような書き方だと、配列iconの値は1つだけになります。

var icon = [];
var list = JSON.parse('');
for (var i = 0; i < list.length; i++){
	if(list[i] =='Clear'){
	 icon = '/img/icon05.png';
	}else if(list[i] =='Clouds'){
	 icon = '/img/icon06.png';
	} else{
	 icon = '/img/icon07.png';
	}
}

嵌ってしまった。。。

controllerのlimitの使い方

findの後に->limit(n)で繋げます。

public function index()
	{
		$this->viewBuilder()->layout('my_layout');
		$now = date("Y-m-d H:i:s");
		$params = array(
		    'conditions' => array(
		        'forecast >' => $now, 
		    ),
		);
		$marunouchis = $this->Marunouchis->find('all', $params)->limit(3);
		$yokohamas = $this->Yokohamas->find('all', $params);	
		$this->set(compact('marunouchis'));
		$this->set(compact('yokohamas'));
	}
}

$paramのconditionsに追記するとエラーになりますね。

weather mapの情報を元に、google mapのアイコンを変える

埼玉のテーブルはまだ作っていませんが、暫定として、

<style>
#map {
		height: 250px;
		width: 100%;
        font-size:small;
        margin-bottom:10px;
	}
</style>

<?php
	$this->assign('title', '首都圏の天気予報');
?>
<?= $this->element('module'); ?>

<h1>首都圏の今日明日の天気予報</h1>
<div id="map"></div>
<b><a href="marunouchis">東京</a></b>
<table class="table1">
	<tr>
	<?php 
	$i = 1;
	foreach ($marunouchis as $marunouchi){
	if($i < 9){
	echo "<td width=\"150px\">";
	echo h($marunouchi->forecast)."<br>";
	$date = h($marunouchi->forecast);
	$result = substr($date, -8);
	if($result == ' 9:00 PM' or $result == '12:00 AM' or $result == ' 3:00 AM'){
	echo convert3(($marunouchi->main))."<br>";
	} else {
	echo convert(($marunouchi->main))."<br>";
	}
	echo convert2(($marunouchi->description))."<br>";
	echo "気温".h($marunouchi->temp)."°C<br>";
	echo "湿度". h($marunouchi->humidity)."%<br>";
	echo "雲の量".h($marunouchi->cloud)."<br>";
	echo "風速".h($marunouchi->speed)."m<br>";
	echo "<td>";
	if($result == '12:00 PM'){
		$mmain = json_encode(h($marunouchi->main));
	}
	}
	$i++;
	}
	?>
	</tr>
</table>

<b><a href="yokohamas">横浜</a></b>
<table class="table1">
	<tr>
	<?php 
	$i = 1;
	foreach ($yokohamas as $yokohama){
	if($i < 9){
		echo "<td width=\"150px\">";
		echo h($yokohama->forecast)."<br>";
		$date = h($yokohama->forecast);
		$result = substr($date, -8);
		if($result == ' 9:00 PM' or $result == '12:00 AM' or $result == ' 3:00 AM'){
		$value = convert3(($yokohama->main))."<br>";
		} else {
		$value = convert(($yokohama->main))."<br>";
		}
		echo $value;
		echo convert2(($yokohama->description))."<br>";
		echo "気温".h($yokohama->temp)."°C<br>";
		echo "湿度". h($yokohama->humidity)."%<br>";
		echo "雲の量".h($yokohama->cloud)."<br>";
		echo "風速".h($yokohama->speed)."m<br>";
		echo "<td>";
		if($result == '12:00 PM'){
		$ymain = json_encode(h($yokohama->main));
		}
	  }
	$i++;
	}
	?>
	</tr>
</table>

<script>
var mmain = JSON.parse('<?php echo $mmain; ?>');
if(mmain =='Clear'){
 var micon = '/img/icon05.png'
}else if(ymain =='Clouds'){
 var micon = '/img/icon06.png'
} else{
 var micon = '/img/icon07.png'
}
var ymain = JSON.parse('<?php echo $ymain; ?>');
if(ymain =='Clear'){
 var yicon = '/img/icon05.png'
}else if(ymain =='Clouds'){
 var yicon = '/img/icon06.png'
} else{
 var yicon = '/img/icon07.png'
}

var map;
var marker = [];
var infoWindow = [];
var markerData = [ 
  {
       name: '東京',
       lat: 35.681167,
        lng: 139.767052,
        icon: micon
 }, {
        name: '横浜',
     	lat: 35.469716,
        lng: 139.629184,
        icon: yicon
 }, {
        name: '埼玉',
     lat: 35.861729,
      lng: 139.645482,
      icon: '/img/icon06.png'
 }
];
 
function initMap() {
    var mapLatLng = new google.maps.LatLng({lat: 35.681167, lng: 139.767052}); 
   map = new google.maps.Map(document.getElementById('map'), { 
     center: mapLatLng, 
      zoom: 9
   });
 
 // マーカー毎の処理
 for (var i = 0; i < markerData.length; i++) {
        markerLatLng = new google.maps.LatLng({lat: markerData&#91;i&#93;&#91;'lat'&#93;, lng: markerData&#91;i&#93;&#91;'lng'&#93;});
        marker&#91;i&#93; = new google.maps.Marker({ 
         position: markerLatLng, 
            map: map
       });
 
     infoWindow&#91;i&#93; = new google.maps.InfoWindow({ 
         content: '<div class="map">' + markerData[i]['name'] + '</div>' 
       });
 
     markerEvent(i);
 }
   for (var i = 0; i < markerData.length; i++) {
   marker&#91;i&#93;.setOptions({
        icon: {
         url: markerData&#91;i&#93;&#91;'icon'&#93;
       }
   });
   }
}
 
function markerEvent(i) {
    marker&#91;i&#93;.addListener('click', function() {
      infoWindow&#91;i&#93;.open(map, marker&#91;i&#93;);
  });
}
</script>
<script async defer
src = "https:maps.googleapis.com/maps/api/js?key=not watch&callback=initMap">
</script>

大分できてきました。

あとは全国の天気ですね。

cakeのviewでjavascript

scriptタグで書けば、普通に表示されます。

<script>
var map;
    function initMap(){
        map = new google.maps.Map(document.getElementById('map'),{
            center:{lat: 35.681167, lng: 139.767052},
            zoom: 8
        });
    }
</script>
<script async defer
src = "https:maps.googleapis.com/maps/api/js?key=&callback=initMap">
</script>

天気のラベルを渡したいですね。

cakeで複数のテーブルを参照するページをつくる

例えば、丸の内と横浜のデータを引っ張て来て、首都圏の天気として表示させてたいとする。
その場合は、controllerで “use Cake\ORM\TableRegistry;” を使って、テーブルを定義する。

<?php

namespace App\Controller;

use Cake\ORM\TableRegistry;  

class TestsController extends AppController
{	
	public function initialize()
    {
         parent::initialize();
         $this->Yokohamas = TableRegistry::get('Yokohamas');
         $this->Marunouchis = TableRegistry::get('Marunouchis');
    }

	public function index()
	{
		$this->viewBuilder()->layout('my_layout');
		$now = date("Y-m-d H:i:s");
		$params = array(
		    'conditions' => array(
		        'id' => '1', 
		    ),
		);
		$marunouchis = $this->Marunouchis->find('all', $params);
		$yokohamas = $this->Yokohamas->find('all', $params);	
		$this->set(compact('marunouchis'));
		$this->set(compact('yokohamas'));
	}
}
?>

viewでは、marunouchisとyokohamasを呼び出せる。

cakeでデータベースを参照しないページをつくる

src/Templateに対象フォルダとindex.ctpをつくります。

controllerをつくります。

<?php
namespace App\Controller;
class TestsController extends AppController
{	
	var $name = 'Tests';
	var $useTable = false;
	public function index()
	{
		$this->viewBuilder()->layout('my_layout');		
	}
}
?>

表示されました。modelはつくらなくても、エラーは表示されません。

cakeのviewで共通関数を読み込む

共通関数はTemplate/Element の中にctpファイルで作成します。ここではmodule.ctpとして、英語から日本語への変換処理を書きます。

<?php 

function convert($main){
	switch($main){
			case 'Clear':
				return "晴れ<img src=\"img/icon01.png\">";
				break;
			case 'Clouds':
				return "曇<img src=\"img/icon02.png\">";
				break;
			case 'Rain':
				return "雨<img src=\"img/icon03.png\">";
				break;
			default:
				echo $main;
		}
}

function convert2($description){
	switch($description){
			case 'clear sky':
				return "晴天<br>";
				break;
			case 'scattered clouds':
				return "きれぎれに浮かんでいる雲";
				break;
			case 'broken clouds':
				return "ちぎれた雲<br>";
				break;
			case 'few clouds':
				return "少しの雲<br>";
				break;
			case 'light rain':
				return "小雨<br>";
				break;
			default:
				echo $description;
		}
}

?>

Viewの共通処理の為、viewのctp(index.ctp)に1行 $this->element(‘module’) を追加します。

<?php
	$this->assign('title', '丸の内の天気');
?>
<?= $this->element('module'); ?>

<h1>丸の内の天気</h1>

<table class="table1">
	<tr>
	<?php 
	$i = 1;
	foreach ($marunouchis as $marunouchi){
	echo "<td width=\"150px\">";
	echo h($marunouchi->forecast). "<br>";
	echo convert(($marunouchi->main))."<br>";
	echo convert2(($marunouchi->description))."<br>";
	echo "気温".h($marunouchi->temp)."<br>";
	echo "湿度". h($marunouchi->humidity)."%<br>";
	echo "雲の量".h($marunouchi->cloud)."<br>";
	echo "風速".h($marunouchi->speed)."m<br>";
	echo "<td>";
	if($i % 8 == 0){
	echo "</tr><tr>";
	}
	$i++;
	}
	?>
	</tr>
</table>

おおお、なるほど

夜中の晴れは”月”のアイコンにしてみましょう。

<?php 
	$i = 1;
	foreach ($marunouchis as $marunouchi){
	echo "<td width=\"150px\">";
	echo h($marunouchi->forecast)."<br>";
	$date = h($marunouchi->forecast);
	$result = substr($date, -8);
	if($result == ' 9:00 PM' or $result == '12:00 AM' or $result == ' 3:00 AM'){
	echo convert3(($marunouchi->main))."<br>";
	} else {
	echo convert(($marunouchi->main))."<br>";
	}
	echo convert2(($marunouchi->description))."<br>";
	echo "気温".h($marunouchi->temp)."<br>";
	echo "湿度". h($marunouchi->humidity)."%<br>";
	echo "雲の量".h($marunouchi->cloud)."<br>";
	echo "風速".h($marunouchi->speed)."m<br>";
	echo "<td>";
	if($i % 8 == 0){
	echo "</tr><tr>";
	}
	$i++;
	}
	?>

cakeのdefault.cssからstyles.cssに変更する

controllerで $this->viewBuilder()->layout(‘my_layout’); と指定した後に、
webrootでcssを書いていきます。

body {
	margin:0;
	padding:10px;
	font-size: 14px;
	font-family: Verdana, sans-serif;
}

.container{
	maring: 0 auto;
}

h1 {
	margin-top:0px;
	margin-bottom: 10px;
	font-size: 20px;
	border-bottom: 1px solid #ccc;
	padding-bottom: 5px;
}

.table1 td {
	padding-bottom: 30px;
}

titleはindex.ctp

<?php
	$this->assign('title', '丸の内の天気');
?>

Elementをsrc/Template/Element/my_header.ctp追加します。

<header></header>

my_layout.ctpで、elementを追加します。

<body>
    <?= $this->element('my_header'); ?>
    <div class="container clearfix">
        <?= $this->fetch('content') ?>
    </div>
</body>

cakephpで今以降の予報を表示する

データベースの日付のフォーマットをdatetimeに変えます。

create table weather.marunouchis(
	id int unsigned auto_increment primary key,
	forecast datetime,
	main varchar(255),
	description varchar(255),
	temp float,
	humidity int,
	cloud int,
	speed float,
	created datetime default null
);

Controllerで条件を追記します。

class MarunouchisController extends AppController
{	

	public function index()
	{
		$now = date("Y-m-d H:i:s");
		$params = array(
		    'conditions' => array(
		        'forecast >' => $now, 
		    ),
		);
		$marunouchis = $this->Marunouchis->find('all', $params);
		$this->set(compact('marunouchis'));
	}
}

表示

おお、素晴らしい

index.ctpを一部改良

<h1>丸の内の天気</h1>

<table>
	<tr>
	<?php 
	$i = 1;
	foreach ($marunouchis as $marunouchi){
	echo "<td width=\"150px\">";
	echo h($marunouchi->forecast). "<br>";
	echo h($marunouchi->main)."<br>";
	echo h($marunouchi->description)."<br>";
	echo "気温".h($marunouchi->temp)."<br>";
	echo "湿度". h($marunouchi->humidity)."%<br>";
	echo "雲の量".h($marunouchi->cloud)."<br>";
	echo "風速".h($marunouchi->speed)."m<br>";
	echo "<td>";
	if($i % 8 == 0){
	echo "</tr><tr>";
	}
	$i++;
	}
	?>
	</tr>
</table>

悲しくなってきた。