LoginSignup
2
1

IPアドレスから天気を取得するサイトを作ってみよう

Posted at

1.はじめに

今回はIPアドレスから現在地を取得して気象情報を表示するサイトを作成してみました。
また、天気の状況によって表示される背景を変更できるようにしました。
使用したAPIは
Open Weather Map
IPInfo
です。

環境
windows10
vscode
IP info API
Open Weather API

2.HTML

index.html
<!DOCTYPE html>
<html lang="ja">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@400;700&display=swap" rel="stylesheet">
<head>
    <meta charset="UTF-8">
    <title>現在地の天気</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div id="weather-container">
        <h1>現在地の天気の情報</h1>
        <div id="weather"></div>
    </div>
    <script src="weather.js"></script>
</body>
</html>

3.CSS

style.css
#weather-container {
    text-align: center;
    margin-top: 150px;
}

#weather {
    font-size: 40px;
    margin-top: 20px;
}
body {
    font-family: 'Noto Sans JP', sans-serif;
}

4.JavaScript

open weather map
async function fetchWeatherData(city) {
    const apiKey = 'API'; // OpenWeatherMapのAPIキー
    const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric&lang=ja`;

    try {
        const response = await fetch(url);
        const data = await response.json();
        changeBackground(data.weather[0].main.toLowerCase());
        return data;
    } catch (error) {
        console.error("天気データの取得に失敗しました", error);
    }
}
IPInfo
async function displayWeather() {
    // IPアドレスから位置情報を取得
    const ipInfoToken = 'TOKEN'; // IPinfoのトークンを設定
    const ipResponse = await fetch(`https://ipinfo.io/json?token=${ipInfoToken}`);
    const ipData = await ipResponse.json();
    const city = ipData.city; 

    // 天気情報を取得
    const weatherData = await fetchWeatherData(city);
    if (weatherData) {
        const weatherElement = document.getElementById('weather');
        weatherElement.textContent = `現在地:${city}、天気:${weatherData.weather[0].description}、気温:${weatherData.main.temp}℃`;
    }
}
天気によって背景を変える
function changeBackground(weather) {
    const body = document.body;
    switch(weather) {
        case 'clear':
            body.style.backgroundImage = 'url("sunny.png")';
            break;
        case 'rain':
            body.style.backgroundImage = 'url("rainy.png")';
            break;
        case 'cloud':
            body.style.backgroundImage = 'url("cloudy.png")';
            break;
        case 'snow':
            body.style.backgroundImage = 'url("snowy.png")';
            break;
        // 他の天気条件に応じた背景を追加
        default:
            body.style.backgroundImage = 'url("default.png")';
    }
}

displayWeather();

5.完成

SnapCrab_NoName_2023-11-21_15-26-15_No-00.png

東京に住んでるんですけど、埼玉県になってました。
サーバーかなんかが埼玉にあるんですかね?

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