天気によって表示する画像を切り替える
APIキーの取得
openWeatherのサイトでアカウントを作ったら、下記URLでゲットします
【https://home.openweathermap.org/api_keys】
bddff0008c99aa1c048650cabbbb4ead
Javascript
const city = "Toride,jp";
const apiKey = "YOUR_API_KEY";
const url = `https://api.openweathermap.org/data/2.5/weather?q=Toride,jp&appid=${apiKey}&units=metric`;
// DOMContentLoadedでページをロードした後にスクリプトを実行します
document.addEventListener("DOMContentLoaded", function () {
fetch(url)
.then(response => response.json())
.then(data => {
let weather = data.weather[0].main.toLowerCase();
let weatherImages = {
'clear': 'https://8ch.tech/wp-content/uploads/2025/03/sunny.jpg',
'clouds': 'clouds.jpg',
'rain': 'rain.jpg',
'snow': 'snow.jpg',
'mist': 'mist.jpg'
};
let imageUrl = weatherImages[weather] || 'default.jpg';
document.getElementById('weather').src = imageUrl;
});
});
補足
これだとAPIキーがブラウザで見えてしまうので、PHPとかを使って隠した方がいいです
BACK