How-tos

What’s the weather like in Bluemix?

Share this post:

The weather. It impacts our life, our health, our mood but also businesses. Last month, IBM announced the availability of the Insights for Weather service in the Bluemix catalog providing developers with an easy way to tap into weather data:

The Insights Weather sample is an application that shows you how to integrate the Insights for Weather service into your applications:

Insights Weather sample - home

Once you select a city, it presents a familiar weather app showing the current weather and the forecast:

Antibes weather

This sample gives a good opportunity to exercise all service APIs. This post looks at the code of this sample, highlighting the service API calls and the format of their responses, together with providing tips on how to display the weather data in your application.

How to Follow Along the Sample Review

To follow along in the source code as we go through it in this post, you have several options:

  • Deploy your own instance of the sample application by clicking the Deploy to Bluemix button. Then you can clone the Bluemix DevOps Git repository created by this process on your local machine

    Deploy to Bluemix

  • Directly clone the GitHub repository to your local computer:
    [code]git clone https://github.com/IBM-Bluemix/insights-weather.git[/code]
    Then later follow these steps to push your own instance of the application
  • Simply browse the GitHub repository when necessary.

Sample Architecture Flow

The sample uses a Node.js back-end and Angular/Bootstrap for the client. It is decomposed as follows:

weather architecture

  • public/index.html – the entry point for the angular application.
  • public/js/app.js – configures the angular app, declares its dependencies and implements the routing between the home page and the search results
  • public/js/search.controller.js – holds the model for the view and supports the user interface interactions
  • public/js/search.service.js – implements the call to the back-end API
  • app.js – serves the html files and implements the back-end API used by the client. It delegates the call to the Insights for Weather service to lib/weather.js
  • lib/weather.js – In our sample, we don’t call the Insights for Weather service directly from the client user interface but hide it behind our own back-end API. This avoids putting the credentials of the service into the client app (this would be a bad idea) and it allows us to expose a slightly different API, such as giving the ability to look up weather conditions not only with geocode but also with plain text (and using a suggestion engine).

Obtaining Service Credentials

When the Weather service is provisioned and bound to an application, the service credentials are exposed through VCAP_SERVICES such as:

[code] "weatherinsights": [
{
"name": "insights-weather-weatherinsights",<br /> "label": "weatherinsights",<br /> "plan": "Free",<br /> "credentials": {<br /> "host": "twcservice.mybluemix.net",<br /> "password": "iwaT3D0BBQ",<br /> "port": 443,<br /> <strong>"url": "https://7af5b79d-5434-6f76-a0a0-d280c153537d:iwaT3D0BBQ@twcservice.mybluemix.net",</strong><br /> "username": "7af5b79d-5434-6f76-a0a0-d280c153537d"<br /> }<br /> }<br /> ][/code]

For most apps, the url property will be all that you need to call the service because it includes the host, username and password – the port is not included because 443 is the default port for HTTPS so this would be redundant.

Overview of the Insights for Weather Service API

The Insights for Weather service comes with four easy-to-use REST API endpoints:

  • /api/weather/v2/observations/current – Real-time weather updates for current weather conditions, including temperature, wind direction and speed, humidity, pressure, visibility and more! Updates include a sensible weather phrase and a matching weather icon.
  • /api/weather/v2/forecast/hourly/24hour – Hourly forecasts for the next 24 hours, including descriptive forecast text.
  • /api/weather/v2/forecast/daily/10day – Daily forecasts for the next 10-day period, including forecast narrative text string of up to 256 characters with appropriate units of measure for the location and in the language requested.
  • /api/weather/v2/observations/timeseries/24hour – Historical weather data for the previous 24 hours, based on weather data from site-based observation stations.

All four endpoints expect the same input parameters to be passed in the query:

  • geocode – A comma-delimited latitude and longitude to retrieve data for (for example, 34.53,84.50). The latitude and longitude need to have at most two decimals.
  • language – The language to return the response in (for example, en-US, es, es-MX, fr-FR)
  • units – The units of measure to return the data in (for example, e=Imperial(English), m=Metric, h=Hybrid)

We really only need one function with the endpoint as a parameter. Here is an extract from lib/weather.js that implements this logic:

[gist https://gist.github.com/l2fprod/c974750e439e784857a2]

  • line 2 – default options will set the language to English and the unit to imperial. The language impacts the narratives and weather condition descriptions provided by the service. In some cases, the units parameter impacts the format of the JSON output. For the sample, we use imperial and convert values on the client when needed.
  • line 7 – the callByGeolocation function is the key. It uses the request Node.js package to call the Weather service. The url has been retrieved from the environment variables in app.js.
  • line 11 – we ensure the latitude and longitude have only 2 decimals – the service API requires this.

Rendering the Weather Data

The service API returns JSON data we can easily process on the client. In the sample:

In our back-end, we requested the units as imperial. This impacts the structure of the returned data as shown below where information such as the low/high temperature are found under the imperial node.

The user interface then processes the values and displays them in Celsius or Fahrenheit based on the user preference. This is achieved with an angular filter:

[code]{{controller.data.current.observation.imperial.temp | formatTemperature: controller.data.temperatureMode }}[/code]

defined in public/js/search.controller.js:

[code].filter(‘formatTemperature’, [<br /> function () {<br /> return function (input, scale) {<br /> // input is assumed in Fahrenheit, as specified in lib/weather.js<br /> // conversion to Celsius occurs in the display<br /> if (scale === ‘C’) {<br /> return Math.round((input – 32) * 5.0 / 9.0);<br /> } else {<br /> return input;<br /> }<br /> };<br />}])[/code]

As homework, I’ll let you explore the search.html file. You can also use the View JSON source button in each section of the user interface to drill down into the data behind the view. For the full specification of the data returned by the Weather service, refer to the service API documentation.

Rendering the Weather Condition Icons

When working with observation or forecast, you can choose to display an icon to illustrate the conditions. The service provides a default icon set you can use to map icon codes to an image. The images in the set are named after the icon code returned by the API.

As example, if we look for the current observation in Antibes, France, we get:

Looking at the JSON returned by the server for the current observation, the icon_code is 34. Using the icon named icon34.png from the default icon set, you can quickly show a visual hint for the observation. The same applies to forecast data. Everywhere you see this icon_code in the service response you can do this mapping.

In the sample application, look for references to icon_code in public/partials/search.html. The weather icon displayed above uses this code:

[code]&lt;img class="media-object weather-current-icon" ng-src="<strong>images/weathericons/icon{{controller.data.current.observation.icon_code}}.png</strong>" /&gt; {{controller.data.current.observation.phrase_32char}}[/code]

Rendering the Wind Direction Icons

In observation and forecast, the Daytime average wind direction is given by the wdir value. In the previous example, wdir is 230. It is expressed in magnetic notation from 0 to 359. You can use the wind icon from the default set to render the wind direction with a simple CSS rotation, as shown in  public/partials/search.html:

[code]&lt;img class="weather-forecast-icon" src="<strong>images/weathericons/icon23.png</strong>" title="{{forecast.wdir_cardinal}}" <strong>style="-webkit-transform: rotate({{forecast.wdir+90}}deg); -moz-transform: rotate({{forecast.wdir+90}}deg); -ms-transform: rotate({{forecast.wdir+90}}deg); -o-transform: rotate({{forecast.wdir+90}}deg); transform: rotate({{forecast.wdir+90}}deg);"</strong> bs-tooltip/&gt; {{forecast.wspd}} mph[/code]

Conclusion

This sample should give you a good starting point to implement the Insights for Weather service into your application. To dig deeper in the Insights for Weather service, you can also check out the Places Insights hands-on lab we delivered at IBM Insight in Las Vegas in October this year. It mixes the Insights for Weather and Insights for Twitter services and gives you some additional coding challenges to improve the resulting application.

f you have feedback, suggestions and questions about this post and the Insights services in Bluemix, please reach out to me on Twitter @L2FProd.

frederic.lavigne@fr.ibm.com

More stories
December 7, 2018

Highly Available Applications with IBM Cloud Foundry

To properly deploy an application in a cloud environment and ensure maximum responsiveness, your app needs to be deployed in a certain (and easy) way that maximizes the chance of an instance always being ready to respond to a user request. This article will explain how to deploy your Cloud Foundry applications in the IBM Cloud such that you reach your target application availability.

Continue reading

December 5, 2018

Cloud Foundry Container-to-Container Networking

If you're like many developers who are deploying applications to Cloud Foundry, you probably don't think about networking too often. After all, as a PaaS, Cloud Foundry takes care of all the routing and connectivity for you. There is one feature, however, you might consider before writing your next app: container-to-container networking.

Continue reading

November 29, 2018

Mobile Foundation on IBM Cloud: Your Mobile App Security is Our Concern

Security features provided by Mobile Foundation on IBM Cloud simplify various aspects of Mobile security, enabling developers to build hack-proof apps. This post covers a list of critical security requirements that Mobile Foundation addresses.

Continue reading