CHAPTER 17 - Create Weather Apps by Linking to Weather Information (1)

After seeing how to link to government's open data, next we will try to link to weather information. This chapter will explain how to link to the Central Weather Bureau first; the next chapter will explain how to link to Yahoo's weather information and use a weather component directly.

Let us look at how to link to information at the Central Weather Bureau.

We can link to the Taiwan Central Weather Bureau Open Data Platform to see lots of observation or forecast data. The Central Weather Bureau provides the most up-to-date and most accurate data; after all, Taiwan's Central Weather Bureau has a renowned reputation around the world!

Let us look for a simple test: "Colored Radar Echo Chart- Southern Taiwan region, with terrain" (http://opendata.cwb.gov.tw/observe/dataset/A0011-006.htm). This is most frequently used in news reports when forecasting rainfall. If you know how to read the radar echo charts, you can predict whether it is going to rain in the next two or three hours.

CHAPTER 17 - Create Weather Apps by Linking to Weather Information (1)



However, because the Weather Bureau only provides XML (Why does it only provide XML in this modern era?), we have to use jQuery's AJAX to retrieve data. Of course, we have to do cross-domain! We had explained how to do cross-domain (Linking JSON) earlier- use Chrome and install this small cross-domain kit "Allow-Control-Allow-Origin: *". Click it, the icon turns green, and cross-domain is enabled! The URL for the weather bureau's XML is: http://opendata.cwb.gov.tw/opendata/DIV4/O-A0011-006.xml.

Because EZoApp has built-in jQuery, you can use jQuery's syntax directly. Let's try to see if we can use AJAX to obtain weather information. In the JS panel, write:

$(function () {
  $.ajax({
    type: "GET",
    url: "http://opendata.cwb.gov.tw/opendata/DIV2/O-A0001-001.xml",
    dataType: "xml",
    error: function (e) {
      console.log('oh no');
    },
    success: function (e) {
      var xml = e;
      console.log($(xml));
    }
  });
});



Click Preview. If it accesses the XML successfully, it will be shown in the console; if it fails, it will show oh no. To view the console, click F12 in Windows; click "Option+Command+i" in Mac. (Example: http://jqmdesigner.appspot.com/designer.html#&ref=4864692967178240)

CHAPTER 17 - Create Weather Apps by Linking to Weather Information (1)



Because XML looks awkward, we will employ a couple of techniques to make it easier to read- use "find" and "text( )" to retrieve the XML's node data directly. The modified code is shown below:

$(function () {
  $.ajax({
    type: "GET",
    url: "http://opendata.cwb.gov.tw/opendata/DIV4/O-A0011-006.xml",
    dataType: "xml",
    error: function (e) {
      console.log('oh no');
    },
    success: function (e) {
      var time = $(e).find('obsTime').text();
      var img = $(e).find('uri').text();
      console.log(time);
      console.log(img);
    }
  });
});



Click Preview, and you should see that you have gotten the time and image! (Preview: http://jqmdesigner.appspot.com/designer.html#&ref=6273799259422720)

CHAPTER 17 - Create Weather Apps by Linking to Weather Information (1)



Since we have gotten the data now, we can change the code a bit to show it on the screen! (Preview: http://jqmdesigner.appspot.com/designer.html#&ref=5748219279572992)

HTML:

<div id="home" data-role="page">
  <div data-role="header" data-position="fixed" data-theme="b">
    <h3>Southern Taiwan Radar Echo Chart</h3>
  </div>
  <div role="main" class="ui-content">
    <h4></h4>
    <div class="img"></div>
  </div>
</div>

javascript:

var time = $(e).find('obsTime').text();
var img = $(e).find('uri').text();
$('h4').append(time);
$('.img').append('<img src="'+img+'"/>');

CHAPTER 17 - Create Weather Apps by Linking to Weather Information (1)



Now that we have learned how to link to a radar echo chart, let us try something more difficult. Let us try to create an app that "has a pull-down menu, allowing users to select a location and view its weather information." Let us select weather observation data at the Central Weather Bureau's website: http://opendata.cwb.gov.tw/observe/dataset/A0001-001.htm. Because it contains a lot of content, let us read the instructions provided by the Weather Bureau first (PDF): http://opendata.cwb.gov.tw/opendatadoc/DIV2/A0001-001.pdf. Looks like we need the following information: CITY, TOWN, TEMP (temperature), HUMD (humidity), WDSD (wind speed), H_24R (daily accumulative precipitation), and OBS_TIME (observation time).

First, we need to grab the number of records. If it is read successfully, you should be able to see "60" in the console.log (not sure if this will change with time):

$(function () {
  $.ajax({
    type: "GET",
    url: "http://opendata.cwb.gov.tw/opendata/DIV2/O-A0001-001.xml",
    dataType: "xml",
    error: function (e) {
      console.log('oh no');
    },
    success: function (e) {
      var num = $(e).find('location').length;
      console.log(num);
    }
  });
});



Then test to see if you can read the contents. Looks like you should be able to read the contents without much trouble. The method used here actually only retrieves the first few values in the data.

Because data is a jQuery variable, we need to use the data.eq(i) method to retrieve it, instead of data[i]. (Preview: http://jqmdesigner.appspot.com/designer.html#&ref=6297908722794496)

$(function () {
  $.ajax({
    type: "GET",
    url: "http://opendata.cwb.gov.tw/opendata/DIV2/O-A0001-001.xml",
    dataType: "xml",
    error: function (e) {
      console.log('oh no');
    },
    success: function (e) {
      var data = $(e).find('location');
      var num = data.length;
      var time = data.eq(0).find('time').text();
      var city = data.eq(0).find('parameter').eq(0).find('parameterValue').text();
      var town = data.eq(0).find('parameter').eq(2).find('parameterValue').text();
      console.log(time);
      console.log(city);
      console.log(town);
    }
  });

CHAPTER 17 - Create Weather Apps by Linking to Weather Information (1)



Now that we can successfully read the data, next, we will throw it into listview! Here, we changed the option above into listview, because the amount of data is huge and listview is easier to read. Furthermore, because we used JQM's listview component API (refresh, so the dynamically filled-in data can use JQM format), we will also change the JS syntax into jQuery Mobile syntax. However, the main program remains the same. (Preview: http://jqmdesigner.appspot.com/designer.html#&ref=4840133538873344)

HTML:

<div id="home" data-role="page">
  <div data-role="header" data-position="fixed" data-theme="b">
    <h3>台灣即時氣象</h3>
  </div>
  <div role="main" class="ui-content">
    <ul data-role="listview" data-inset="true" id="menu">
      <li data-role="list-divider">點選城市<i class="time"></i></li>
    </ul>
  </div>
</div>

javascript:

(function () {
  $(document).on("pageshow", "#home", function () {
    $.ajax({
      type: "GET",
      url: "http://opendata.cwb.gov.tw/opendata/DIV2/O-A0001-001.xml",
      dataType: "xml",
      error: function (e) {
        console.log('oh no');
      },
      success: function (e) {
        var i;
        var $menu = $('#menu');
        var data = $(e).find('location');
        var num = data.length;
        var time = data.eq(0).find('time').text();
        for (i = 0; i < num; i++) {
          $menu.append('<li><a href="#">' +
            data.eq(i).find('parameter').eq(2).find('parameterValue').text() +
            '</a></li>').listview('refresh');
        }
      }
    });
  });
})();

CHAPTER 17 - Create Weather Apps by Linking to Weather Information (1)



Just throwing data in is not so impressive. Now, we want to make it able to show information when clicked, just like the map in the previous section. So, we will create a new page and call it detail. Then, add some JS code so it can display corresponding weather information when clicked. If you are not familiar with adding a new page, please read the section on adding a new page in the previous chapter. It can be done in exactly the same way! Note: because the retrieved XML tag names contain many duplicates, we need to look at their order; this is also the reason why we used many eq! (Example: http://jqmdesigner.appspot.com/designer.html#&ref=4840418885763072)

CHAPTER 17 - Create Weather Apps by Linking to Weather Information (1)

HTML ( #home ):

<div id="home" data-role="page">
  <div data-role="header" data-position="fixed" data-theme="b">
    <h3>台灣即時氣象</h3>
  </div>
  <div role="main" class="ui-content">
    <ul data-role="listview" data-inset="true" id="menu">
      <li data-role="list-divider">更新:<i class="time"></i>
      </li>
    </ul>
  </div>
</div>

HTML (#detail ):

<div id="detail" data-role="page" is="page">
  <div data-role="header" data-position="fixed" data-theme="b">
    <h3>Header</h3>
    <a class="ui-btn ui-btn-left ui-icon-arrow-l ui-btn-icon-notext" data-rel="back">Button</a>
  </div>
  <div role="main" class="ui-content" is="content">溫度:
    <span class="temp"></span>度C
    <br>濕度:
    <span class="humd"></span>百分比
    <br>風速:
    <span class="wdsd"></span>公尺/秒
    <br>日雨量:
    <span class="h24r">毫米</span>
  </div>
</div>

javascript:

var temp, humd, wdsd, h24r,name;
(function () {
  $(document).on("pageshow", "#home", function () {
    $.ajax({
      type: "GET",
      url: "http://opendata.cwb.gov.tw/opendata/DIV2/O-A0001-001.xml",
      dataType: "xml",
      error: function (e) {
        console.log('oh no');
      },
      success: function (e) {
        var i,
          $menu = $('#menu'),
          data = $(e).find('location'),
          num = data.length,
          time = data.eq(0).find('time').text();
        $('.time').append(time);

        for (i = 0; i < num; i++) {
          $menu.append('<li><a href="#detail">' +
            data.eq(i).find('parameter').eq(2).find('parameterValue').text() +
            '</a></li>').listview('refresh');
        }

        $('li a').on('click',function(){
          var aIndex = $(this).parent('li').index()-1;
          temp = data.eq(aIndex).find('weatherElement').eq(3).find('elementValue').text();
          humd = data.eq(aIndex).find('weatherElement').eq(4).find('elementValue').text();
         h24r = data.eq(aIndex).find('weatherElement').eq(7).find('elementValue').text();
         wdsd = data.eq(aIndex).find('weatherElement').eq(2).find('elementValue').text();
         name = $(this).text();
        });
      }
    });
  });
})();

(function () {
  $(document).on("pageshow", "#detail", function () {
    $('.temp').append(temp);
    $('.humd').append(humd);
    $('.h24r').append(h24r);
    $('.wdsd').append(wdsd);
    $('h3').text(name);
  });
})();

CHAPTER 17 - Create Weather Apps by Linking to Weather Information (1)



That's it! It's done! Now, just export the APK and you have created a real-time weather app; only it still lacks some user experience and beautification. Nevertheless, did you discover that it is actually not difficult? In the next chapter, we will continue to introduce different methods to link to other weather information. (Example: http://jqmdesigner.appspot.com/designer.html#&ref=5966318792605696)



Continue reading CHAPTER 18 - Create Weather Apps by Linking to Weather Information (2)
Or Return to Table of Contents


results matching ""

    No results matching ""