# JS練習_天氣API 透過抓取中央氣象局的公開API資料,抓取台灣各縣市的當下天氣情況及未來一週天氣預報,透過下拉式選單選取不同縣市,以取得不同的天氣圖片所表示不同的天氣狀況。 ## 成品畫面 ![](https://i.imgur.com/xPxuv51.png) 先導入jQuery以及bootstarap,透過先設定好縣市的天氣內容,以利編輯CSS的部分。 ## 功能 - 下拉式選單選取不同縣市 - 顯示選取城市的當下天氣資料 - 顯示選取城市未來一週天氣資料及溫度 ## JavaScript ### $.ajax({}) #### 申請API - 到中央氣象局網站加入會員 ![](https://i.imgur.com/Ui2OZxX.png) - 點選取得授權碼 ![](https://i.imgur.com/SnyrFGr.png) - 前往[中央氣象局開放資料平臺之資料擷取API](https://opendata.cwb.gov.tw/dist/opendata-swagger.html)將剛剛得到的url貼到想要查詢的頁面產生==URL== - ![](https://i.imgur.com/5Bmegf4.png) 利用`$.ajax()`輸入剛剛得到的url抓取中央氣象局JSON的資料,成功時會觸發`todayWeather`、`selectCity`與`weekWeather`這幾個函式。 觀察JSON檔,確認所需要的資料是在檔案的什麼位置,並用`console.log`印出來檢視內容。 ![](https://i.imgur.com/UjXSbTv.png) 在開發者工具試著打印`data.location[cityNum].weatherElement`,確認我們可以得到一個有15個氣象資訊的陣列變數。之後要取用資料時,便得確認該資料的位置帶入相關索引值。 ![](https://i.imgur.com/C3qwh2A.png) ```.js= $.ajax({ url:'https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-D0047-091?Authorization=CWB-373C6328-6BF2-41B3-BB3B-147802B82875&format=JSON&locationName=&elementName=&sort=time', method: "GET", datatype:"json", success: function(res){ data = res.records.locations[0]; // console.log(data); city = data.location; // console.log(city); todayWeather(data, cityNum); selectCity(city); weekWeather(data, cityNum); } }) ``` ### todayWeather() 1. 先把原先在index.html中設定的假的html內容先設定為空。 2. 創造一個取得現在時間的函數,並把最後的GMT時區用`split()`方式移除。 3. 在`$.ajax()`那已確認所需資料於JSON檔的位置,這裡便可以直接指定變數。 4. 將設定好的變數再度放回index.html中。 ```.js= function todayWeather(data, cityNum){ // console.log(123) $('#weatherNow').html(''); chooseCity = data.location[cityNum].locationName // console.log(chooseCity); todayDate = new Date().toString().split("GMT")[0]; let weather = data.location[cityNum].weatherElement; weatherDescription = weather[6].time[0].elementValue[0].value; let weatherTemp = data.location[cityNum].weatherElement[1].time[0].elementValue[0].value; let weatherImg = changeImg(weatherDescription); $('.weather_now').html(` <h1>${chooseCity}</h1> <h2>${todayDate}</h2> ${weatherImg} <div class="now-description">${weatherDescription}</div> <p>溫度: ${weatherTemp} °C</p> `) } ``` ### selectCity() `data`參數是我們一開始在`$.ajax()`所觀察出來在JSON檔中的資料,再利用加上localName屬性,取得台灣縣市名稱。 利用迴圈放入`select`選單中,使選單出現台灣各縣市。 ```.js= function selectCity(data){ const $ = document.querySelector.bind(document); let select = $('select'); for(let i =0;i< data.length;i++){ city = data[i].locationName; let value =i; select.innerHTML += ` <option value="${value}">${city}</option>; } // console.log(city); } ``` ### changeImg() 假設各式天氣狀況,當內容文字符合之時,便會秀出天氣圖片。 ```.js= function changeImg(weatherDescription){ if(weatherDescription === '多雲時晴' || weatherDescription === '晴時多雲' ){ return '<img src="./img/sun.png" alt="sun-cloudy">' }else if(weatherDescription === '多雲' || weatherDescription === '陰時多雲' || weatherDescription === '多雲時陰'){ return '<img src="./img/cloudy.png" alt="cloudy">' }else{ return '<img src="./img/drop.png" alt="rainy">' } } ``` - [天氣圖片資料來源](https://www.flaticon.com/categories/weather) ### weekWeather() 1. 先將原先的html先清除。 2. 將創造出的div給定`day`屬性方便做CSS方面的修改。 3. 設定各項氣象資料變數。 4. 設定時間函數取得當前時間,星期幾及時間。 5. 將設定好的變數再度放回index.html中 6. 使用`append()`方法將資料參數放入`<div id='week'></div>`元素後面。 ```.js= function weekWeather(data, cityNum){ $('#week').html(''); let oneWeek =['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; let weekDay =[] for (i = 1; i < 7; i++) { let timeIndex = 2 * i; let day = $('<div></div>').attr('class', `day`); nextWeekNum = new Date().getDay()+1; let weather = data.location[cityNum].weatherElement; weatherDescription = weather[6].time[timeIndex].elementValue[0].value; let weatherTemp = data.location[cityNum].weatherElement[1].time[timeIndex].elementValue[0].value; let weatherImg = changeImg(weatherDescription); day.html(` <h3>${oneWeek[i]}</h3> ${weatherImg} <div class="week-description">${weatherDescription}</div> <p>溫度: ${weatherTemp} °C</p> `); $('#week').append(day); } ``` #### change事件 將下拉式選單`select`綁定`change`事件,當選單內容改變時便會觸發·`todayWeather`與`weekWeather`函式 ```.js= $('#select').change(function() { // console.log(123) cityNum = $('#select :selected').val(); todayWeather(data, cityNum); weekWeather(data, cityNum); }); ``` ###### tags: `javascript`