1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Go】OpenWeatherMap APIを使用して現在の天気情報を取得する

Last updated at Posted at 2019-09-17

はじめに

OpenWeatherMap APIの基本的な使い方に関してはこちらの記事を参照

サンプルコード

各フィールドの正確なデータ型(int, float64等)はわからなかったので、ここのJSONレスポンス例の値を参考に指定していますが、間違っている可能性もあります。

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"
)

type OpenWeatherMapAPIResponse struct {
	Main    Main      `json:"main"`
	Weather []Weather `json:"weather"`
	Coord   Coord     `json:"coord"`
	Wind    Wind      `json:"wind"`
	Dt      int64     `json:"dt"`
}

type Main struct {
	Temp     float64 `json:"temp"`
	TempMin  float64 `json:"temp_min"`
	TempMax  float64 `json:"temp_max"`
	Pressuer int     `json:"pressure"`
	Humidity int     `json:"humidity"`
}

type Coord struct {
	Lon float64 `json:"lon"`
	Lat float64 `json:"lat"`
}

type Weather struct {
	Main        string `json:"main"`
	Description string `json:"description"`
	Icon        string `json:"icon"`
}

type Wind struct {
	Speed float64 `json:"speed"`
	Deg   int     `json:"deg"`
}

func main() {
	token := "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"                   // APIトークン
	city := "Tokyo,jp"                                            // 東京を指定
	endPoint := "https://api.openweathermap.org/data/2.5/weather" // APIのエンドポイント

	// パラメータを設定
	values := url.Values{}
	values.Set("q", city)
	values.Set("APPID", token)

	// リクエストを投げる
	res, err := http.Get(endPoint + "?" + values.Encode())
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	// レスポンスを読み取り
	bytes, err := ioutil.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(bytes))
	// => {"coord":{"lon":139.76,"lat":35.68},"weather":[{"id":803,"main":"Clouds","description":"broken clo
	//    uds","icon":"04n"}],"base":"stations","main":{"temp":297.16,"pressure":1004,"humidity":94,"temp_mi
	//    n":295.93,"temp_max":298.15},"visibility":10000,"wind":{"speed":2.6,"deg":70},"clouds":{"all":75},
	//    "dt":1568645761,"sys":{"type":1,"id":8074,"message":0.0067,"country":"JP","sunrise":1568665471,"su
	//    nset":1568710031},"timezone":32400,"id":1850147,"name":"Tokyo","cod":200}

	// JSONパース
	var apiRes OpenWeatherMapAPIResponse
	if err := json.Unmarshal(bytes, &apiRes); err != nil {
		panic(err)
	}

	fmt.Printf("時刻:     %s\n", time.Unix(apiRes.Dt, 0))
	fmt.Printf("天気:     %s\n", apiRes.Weather[0].Main)
	fmt.Printf("アイコン: https://openweathermap.org/img/wn/%s@2x.png\n", apiRes.Weather[0].Icon)
	fmt.Printf("説明:     %s\n", apiRes.Weather[0].Description)
	fmt.Printf("緯度:     %f\n", apiRes.Coord.Lat)
	fmt.Printf("経度:     %f\n", apiRes.Coord.Lon)
	fmt.Printf("気温:     %f\n", apiRes.Main.Temp) // ケルビンで取得される
	fmt.Printf("最高気温: %f\n", apiRes.Main.TempMax)
	fmt.Printf("最低気温: %f\n", apiRes.Main.TempMin)
	fmt.Printf("気圧:     %d\n", apiRes.Main.Pressuer)
	fmt.Printf("湿度:     %d\n", apiRes.Main.Humidity)
	fmt.Printf("風速:     %f\n", apiRes.Wind.Speed)
	fmt.Printf("風向き:   %d\n", apiRes.Wind.Deg)

	// => 時刻:     2019-09-16 23:56:01 +0900 JST
	//    天気:     Clouds
	//    アイコン: http://openweathermap.org/img/wn/04n@2x.png
	//    説明:     broken clouds
	//    緯度:     35.680000
	//    経度:     139.760000
	//    気温:     297.160000
	//    最高気温: 298.150000
	//    最低気温: 295.930000
	//    気圧:     1004
	//    湿度:     94
	//    風速:     2.600000
	//    風向き:   70
}

参考

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?