お天気機能の作り方

はじめに

いまとある管理画面を作っているのですが、
「管理画面のTOPに天気予報とか出たら便利じゃない?」

とディレクターの方に言われたので作ることになりました。

準備するもの

Google’s Secret Weather API

以上です。

つくりかた

はい。ここ見てください。
天気予報をXMLで取得するGoogleの非公式API
Google Weather APIを使ってピンポイント天気予報を作成


けどこれだと、Chibaとかしたり。
いちいち住所入れるの面倒ですよね。


うちのサイトでは特性上、緯度と経度を保存してあるので、
それが使いたくなったわけですよ。んでぐぐってみたらありました。

Google天気APIで緯度と経度を使う。どんなフォーマット?みたいな?
Using Google Weather API with Lat and Lon - how to format?

取り敢えず英語でよくわからんけど「.」さえ消しとけばなんとかなるよう。

桁数とか揃えないといけないけどね。

ソースコード

<?
//hl=jaで日本語で取得出来る
$str = file_get_contents('http://www.google.com/ig/api?weather=,,,'.str_replace('.', '', 緯度,経度).'&hl=ja');

//SJISだと解析出来なかったのでUTF-8に変換してる
$str = mb_convert_encoding($str, 'UTF-8', 'Shift-JIS');
$weather_xml = simplexml_load_string ($str);
あとは出力してみる
?>
	<table>
		<caption>現在の天気</caption>
		<tr>
			<th>天気</th>
			<th>気温</th>
			<th>その他</th>
		</tr>
		<tr>
			<td>
				<?=$weather_xml->weather->current_conditions->condition['data']?><br />
				<img src="http://www.google.com<?=$weather_xml->weather->current_conditions->icon['data']?>">
			</td>
			<td><?=$weather_xml->weather->current_conditions->temp_c['data']?></td>
			<td>
				<?=$weather_xml->weather->current_conditions->humidity['data']?><br />
				<?=$weather_xml->weather->current_conditions->wind_condition['data']?>
			</td>
		</tr>
	</table>

	<table>
		<caption>向こう4日の天気</caption>
		<tr>
			<th>曜日</th>
			<th>天気</th>
			<th>気温</th>
		</tr>
		<?foreach($weather_xml->weather->forecast_conditions as $value):?>
		<tr>
			<th><?=$value->day_of_week['data']?></th>
			<td>
				<?=$value->condition['data']?><br />
				<img src="http://www.google.com<?=$value->icon['data']?>">
			</td>
			<td>
				<font color="#FF0000"><?=$value->high['data']?></font>/<font color="#0000FF"><?=$value->low['data']?></font>
			</td>
		</tr>
		<?endforeach?>
	</table>


わかったこと

  • 取り敢えずやりたいと思って調べてみるとなんかいい感じのAPIがあることが多い。
  • そのAPIの提供元がGoogleって事はよくあること。
  • 降水確率がなかった。