あすの天気を教えるよ!
あすの天気を知りたい都市名を入力してください。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>あすの天気アプリ</title>
</head>
<body>
<h1>あすの天気を教えるよ!</h1>
<p>あすの天気を知りたい都市名を入力してください。</p>
<input type="text" id="cityName" placeholder="都市名">
<button onclick="getWeather()">天気を検索</button>
<div id="weatherResult"></div>
<script>
function getWeather() {
const cityName = document.getElementById("cityName").value;
const apiEndpoint = "https://api.openweathermap.org/data/2.5/weather";
const apiKey = "ここにあなたのAPIキーを入力";
const units = "metric";
const url = `${apiEndpoint}?q=${cityName}&appid=${apiKey}&units=${units}`;
fetch(url)
.then(response => {
if(!response.ok) {
throw new Error("ネットワークエラーが発生しました。");
}
return response.json();
})
.then(data => {
const weather = data.weather[0].description;
const temp = data.main.temp;
const city = data.name;
const country = data.sys.country;
const resultDiv = document.getElementById("weatherResult");
resultDiv.innerHTML = `<p>${country}の${city}はあす、${weather}で、気温は${temp}℃です。</p>`;
})
.catch(error => {
const resultDiv = document.getElementById("weatherResult");
resultDiv.innerHTML = `<p>${error.message}</p>`;
});
}
</script>
</body>
</html>
※取得するAPIはOpenWeatherMapのものを利用するため、APIキーが必要です。また、演出として「あなたのAPIキーを入力」となっていますが、実際はAPIキーを直接入力する必要があります。