0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

天気情報を取得する

0
Posted at

Androidで天気情報を取得する方法をメモします。今回は無料のOpen-Meteo APIを使用します。

必要な権限やライブラリを追加します。

AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
build.gradle.kts
dependencies {
    implementation("com.squareup.retrofit2:retrofit:2.11.0")
    implementation("com.squareup.retrofit2:converter-gson:2.11.0")
}

今回は気温と湿度を取得するので、必要なデータとAPIだけ定義します。

data class WeatherResponse(
    val current: CurrentWeather
)

data class CurrentWeather(
    val temperature_2m: Double,   // 気温
    val relative_humidity_2m: Int // 湿度
)
interface WeatherApi {
    @GET("v1/forecast")
    suspend fun getWeather(
        @Query("latitude") latitude: Double,
        @Query("longitude") longitude: Double,
        @Query("current")
        current: String = "temperature_2m,relative_humidity_2m"
    ): WeatherResponse
}

あとはRetrofitを作成し、緯度と経度を指定してAPIを呼び出すことで取得できます。

val retrofit = Retrofit.Builder()
    .baseUrl("https://api.open-meteo.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build()

val weatherApi = retrofit.create(WeatherApi::class.java)

lifecycleScope.launch {
    try {
        val weather = weatherApi.getWeather(
            latitude = 35.681236,
            longitude = 139.767125 // 東京の場合
        )

        println("気温:${weather.current.temperature_2m}℃")
        println("湿度:${weather.current.relative_humidity_2m}%")
        // 気温:24.3℃
        // 湿度:68%
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

Open-Meteo APIは他にも天気、降水量、風速、日射量など様々な情報を取得できます。緯度と経度を固定にしていますが、Androidの位置情報取得APIと組み合わせれば現在地の天気情報を自動で取得するアプリなどを作ることができます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?