const apiKey = "YOUR_API_KEY"; // 要查詢的地區名稱,例如 "臺北市"、"新北市"、"嘉義縣" 等等 const locationName = "臺北市"; // API 端點 const apiEndpoint = `https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=${apiKey}&locationName=${locationName}`; // 使用 fetch() 方法發送 API 請求 fetch(apiEndpoint) .then(response => response.json()) .then(data => { // 解析 API 回傳的 JSON 資料 // 取得所選地區的天氣資訊 const location = data.records.location[0].locationName; const weatherDescription = data.records.location[0].weatherElement.find(element => element.elementName === "Wx").time[0].parameter.parameterName; // 取得溫度資訊 const temperatureData = data.records.location[0].weatherElement.find(element => element.elementName === "MaxT"); const temperature = temperatureData.time[0].parameter.parameterName; const temperatureUnit = temperatureData.time[0].parameter.parameterUnit; // 取得降雨資訊 const precipitationData = data.records.location[0].weatherElement.find(element => element.elementName === "PoP"); const precipitation = precipitationData.time[0].parameter.parameterName; const precipitationUnit = precipitationData.time[0].parameter.parameterUnit; // 在網頁上顯示天氣資訊及溫度 const weatherInfo = document.getElementById("weatherInfo"); weatherInfo.textContent = "地點:" + location + "\n" + "天氣狀況:" + weatherDescription + "\n" + "溫度:" + temperature + " " + temperatureUnit + "\n" + "降雨機率:" + precipitation + " " + precipitationUnit; }) .catch(error => { // 請求失敗時的處理 console.error("無法獲取天氣資訊", error); });