LoginSignup
2
6

More than 3 years have passed since last update.

無料天気予報OpenWeatherMapAPIをPHP取得&使い方

Last updated at Posted at 2020-11-04

OpenWeatherMap とは

OpenWeatherMapは、現在の天気や天気予報などの無料APIを提供するオンラインサービスです。

APIキーを取得する

アカウント登録
OpenWeatherMapにアクセスしてサインアップします。

APIキーを取得
ログイン後のメニューに表示されているAPI Keysを選択すると、APIキーが表示されています。

OpenWeatherMapのAPIを叩く

URLを叩けば取得できます。適切に下記の値を変更してください。
{LAT} = 緯度
{LON} = 経度
{YOUR API KEY} = 取得したAPIキー

https://api.openweathermap.org/data/2.5/onecall?lat={LAT}&lon={LON}&units=metric&lang=ja&appid={YOUR API KEY}

レスポンス内容の例)

json.js
{
    "lat": 000000,
    "lon": 000000,
    "timezone": "Asia/Tokyo",
    "timezone_offset": -32400,
    "current": {
        "dt": 1604643808,
        "sunrise": 1604598892,
        "sunset": 1604626793,
        "temp": -22.39,
        "feels_like": -29.04,
        "pressure": 1016,
        "humidity": 100,
        "dew_point": -22.39,
        "uvi": 0.29,
        "clouds": 100,
        "visibility": 105,
        "wind_speed": 4.26,
        "wind_deg": 212,
        "weather": [
            {
                "id": 601,
                "main": "Snow",
                "description": "",
                "icon": "13n"
            }
        ],
        "snow": {
            "1h": 0.72
        }
    },
    "hourly": [
        {
        ...()...
        },
        ...()...
        {
        ...()...
        }
    ],
    "daily": [
        {
        ...()...
        },
        ...()...
        {
        ...()...
        }
    ]
    "alerts": [
        {
        ...()...
        }
    ]
}

主に使う値

  • 時刻: dt
  • 日の出: sunrise
  • 日没: sunset
  • 温度: temp
  • 体感温度: feels_like
  • 気圧: pressure
  • 湿度: humidity
  • UV指数: uvi
  • 風速: wind_speed
  • 風の向き: wind_deg
  • 気象情報: weather.main
  • 気象情報の詳細: weather.description
  • 気象情報のアイコンID: weather.icon
  • 降水量: rain.1h
  • 降雪量: snow.1h ※積雪ではないので要注意

画像アイコン

10n の部分をweather.iconで取得したアイコン名に変更するだけ
https://openweathermap.org/weather-conditions

<img src="https://openweathermap.org/img/wn/10n@2x.png">

PHPで取得

$weather_config = array(
    'appid' => '○○○○○○○○○○○○○○○',
    'lat' => '63.027139',
    'lon' => '-150.941425',
);
$weather_json = file_get_contents('http://api.openweathermap.org/data/2.5/weather?lat=' . $weather_config['lat'] . '&lon=' . $weather_config['lon'] . '&units=metric&lang=ja&APPID=' . $weather_config['appid']);
$weather_array = json_decode($weather_json, true);

weather.mainは英語しかないので日本語訳はこちらを使ってください。(自作なので適当に直してください)

$weatherTranslate = array(
    'Clear' => '晴れ',
    'Clouds' => 'くもり',
    'Rain' => '雨',
    'Drizzle' => '霧雨',
    'Thunderstorm' => '雷雨',
    'Snow' => '雪'
);

温度を四捨五入する

round($weather_array['main']['temp'], 1);

降雪量のmmをcmに変換

$weather_array['snow']['1h'] * 0.1;

パラメーターオプション

オフィシャルリファレンス
https://openweathermap.org/current

主に使うパラメーター

単位 ( &units=metric )

測定単位(任意)
standard、metricおよびimperialユニットが利用可能です。unitsパラメータを使用しない場合、デフォルトはstandardです。
「units=metric」で摂氏温度(℃)の取得ができます。
これがないと絶対温度(K)になるので、取得した数値から「-273.15」する必要があります。
利用可能値:standard, metric, imperial
デフォルト:standard

モード ( &mode=json )

レスポンス形式(任意)
可能な値はjson、xmlおよびhtml。modeパラメータ形式を使用しない場合、デフォルトはjsonです。
利用可能値:json, xml, html
デフォルト:json

多言語 ( &lang=ja )

言語形式(任意)
このパラメーターを使用して、ご使用の言語で出力を取得できます。

利用可能値:

  • af アフリカーンス語
  • al アルバニア語
  • ar アラビア語
  • az アゼルバイジャン
  • bg ブルガリア語
  • ca カタロニア語
  • cz チェコ語
  • da デンマーク語
  • de ドイツ人
  • el ギリシャ語
  • en 英語
  • eu バスク
  • fa ペルシア語(ペルシア語)
  • fi フィンランド語
  • fr フランス語
  • gl ガリシア語
  • he ヘブライ語
  • hi ヒンディー語
  • hr クロアチア語
  • hu ハンガリー語
  • id インドネシア語
  • it イタリアの
  • ja 日本人
  • kr 韓国語
  • la ラトビア語
  • lt リトアニア語
  • mk マケドニアの
  • no ノルウェー語
  • nl オランダの
  • pl 研磨
  • pt ポルトガル語
  • pt_br ポルトガル語ブラジル
  • ro ルーマニア語
  • ru ロシア
  • sv, se スウェーデンの
  • sk スロバキア
  • sl スロベニア語
  • sp, es スペイン語
  • sr セルビア語
  • th タイ語
  • tr トルコ語
  • ua, uk ウクライナ語
  • vi ベトナム語
  • zh_cn 中国語(簡体字
  • zh_tw 中国の伝統的な
  • zu ズールー

デフォルト:en

JavaScriptコードのコールバック関数

JavaScriptコードを使用するには、callback functionNameをJSONのコールバックに転送できます。

https://api.openweathermap.org/data/2.5/weather?q=London,uk&callback={TEST}&appid={YOUR API KEY}

各アカウント制限

スクリーンショット 2020-11-06 15.32.41.png
無料アカウント
60コール/分
1,000,000コール/月

参考サイト

https://qiita.com/nownabe/items/aeac1ce0977be963a740
https://hsmt-web.com/blog/openweathermap-api/
https://dev.classmethod.jp/articles/use-open-weather-map/
https://yuukiyg.hatenablog.jp/entry/2019/11/17/182410

2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6