Recently, I received a task to show weather reports for 2 cities on a SharePoint page, Miami and Atlantic City. It was supposed to be done in SharePoint Online environment, so nothing on the server side has to written. So, I had to challenges. One is how to get the data and the second is how to do it properly to get the reports for 2 cities, as in general APIs are provided information for one city in a single call.
Let’s start with first point. After some investigation, I discovered the best way for me is to OpenWeather API. I could choose the free version, as I did not have so many calls to require a paid account, and it was enabled for cross domains JavaScript calls also. Using GET method of Ajax calls, to get the data for a city you only need to set the right URL; https://api.openweathermap.org/data/2.5/weather?q=Miami&appid=myapplicaionid
So far I was good, but I needed to get the data for 2 cities and, with some help of JavaScript promises, this was easily done.
(function(objOwner) {
objOwner.Weather = objOwner.Weather || {};
objOwner.Weather.getWeather = function(city) {
var promise = new Promise(function(resolve, reject) {
var url = 'https://api.openweathermap.org/data/2.5/weather?q=' + city + '&appid=myapplicationid';
jQuery.ajax({
method: "GET",
url: url,
success: function(data) {
resolve(data);
},
fail: function(err) {
reject(err);
}
});
});
return promise;
}
})(window);
Sys.Application.add_load(function() {
var miamiWeather = Weather.getWeather('Miami');
var acWeather = Weather.getWeather('Atlantic City');
Promise.all([miamiWeather, acWeather]).then(function(results) {
var html = '';
for(var i = 0; i < results.length; i++) {
var city = results[i];
html += '<div class="weather-location">' +
'<div class="weather-location-icon"><img src="https://openweathermap.org/img/w/' + city.weather[0].icon + '.png" /></div>' +
'<div class="weather-location-city">City ' + city.name + '</div>' +
'<div class="weather-location-temp">Temp ' + city.main.temp + '</div>' +
'<div class="weather-location-mintemp">Min ' + city.main.temp_min + '</div>' +
'<div class="weather-location-maxtemp">Max ' + city.main.temp_max + '</div>' +
'<div class="weather-location-wind">Wind ' + city.wind.speed + '</div>' +
'</div>';
}
jQuery('div.weather-container').html(html);
}).catch(function(err) {
alert(err);
});
});
I have register code to be executed with Sys.Application.add_load method, with the purpose of creating 2 calls to the API, one for each city, and show the data in div element when both calls are completed. I placed entire code in JavaScript file and register in the SharePoint page using script editor web part.
<div class="weather-container"></div>
<script type="text/javascript" src="https://mytenant.sharepoint.com/sites/portal/Scripts/weather/weather.js"></script>
The styling of the results is not something I can write about. I am really not into design area, but I am sure some nice widgets can outcome from this.