Introduction
Worldwide, more and more people are often affected by sudden climate change, leading to possible unforeseen disasters. Hence, people and organizations rely on accurate and real-time forecasting weather applications to have better decisions involving their safety and business continuity. As we rely more on weather forecasting applications, these applications must give us accurate results and provide us with historical data, real-time data, and forecasting data.
Moreover, developers who are into weather application development are most likely to consume weather forecasting APIs, and there are plenty of reliable providers in the market. And if you haven't decided yet which provider to use and are currently experimenting with some platforms, this article might help you select and start with the ClimaCell Weather API platform.
Background
There are various programming languages you can choose from to get you started with a weather API.
In this guide, we will focus on JavaScript.
Here are the things needed to get you started,
- Basics of the JavaScript language.
- A text editor on your machine such as Notepad, Notepad++, VS Code, etc.
- Access to ClimaCell Weather API platform. If you haven't registered yet, please register within their portal.
How to Integrate the API
Getting Your API Key
To use the ClimaCell API, we need to have an API key. This key will be available in your dashboard once you have completed your registration. The screenshot below displays the API key location within your dashboard page.
Getting Your Current Location
Before we can use the API, we need to have our browser coordinates. Our browser provides a native call to the geolocation interface. This object can obtain a device's position when using the navigator.geolocation property.
const nav = navigator.geolocation;
if (nav) {
nav.getCurrentPosition((position) => {
let coordinates = position.coords;
console.log(coordinates.latitude, coordinates.longitude);
});
}
Making an API Call
In this article, we are going to be using ClimaCell’s daily API. This API provides a daily forecast that summaries up to 15 days. Lastly, with every successful request when using the daily API, you'll get the data in JSON; it's up to you how you will present your data to your user.
To see where the daily API documentation location is on the reference page, please see the screenshot below.
Now that we have the coordinates needed for the weather forecast, we can then pass these coordinates as a parameter for our API call.
Don't forget your API key before making a call.
const api_key = ''your_api_key",
url = 'https://api.climacell.co/v3/weather/forecast/daily',
nav = navigator.geolocation;
let lat = 0.0,
lon = 0.0,
unit_system='si',
start_time = 'now',
fields = ['humidity', 'temp', 'weather_code'],
requesturl = "";
if(nav){
nav.getCurrentPosition((position) => {
let coordinates = position.coords;
lat = coordinates.latitude;
lon = coordinates.longitude;
requesturl = encodeURI(`${url}?lat=${lat}&lon=${lon}&unit_system=${unit_system}&start_time=${start_time}&fields=${fields.join(',')}&apikey=${api_key}`);
getWeatherForeCast();
});
}
async function getWeatherForeCast(){
const response = await fetch(requesturl, { "method": "GET", "headers": {}});
const json = await response.json();
console.log(json);
}
This is how the code runs.
- We have declared the application's const, such as the API key, URL, and Navigator object, assigning them to their specific variables.
- After that, we have another set of variable declarations; these act as placeholders.
- We have condition statements that check the navigator object, get the device's current location, and set our placeholders' values and build the URL.
- Lastly, make a request call to the API and check the results.
Output
Creating a simple weather App
Knowing how to integrate your chosen programming language into any weather API seems straightforward.
To appreciate ClimaCell's weather API, let's try to create a simple weather application that will predict the weather within the first 15 days.
Here’s a sample output for this application.
To give more of a background about the screenshot above, it’s the weather application’s final output.
Once the web application runs, it will automatically detect your coordinates. Once it has the proper coordinates, it will start to call the ClimaCell API to give a 15-day weather forecast as shown above. Moreover, the widget’s upper or header part will show the current weather for the day, and it also includes the temperature and humidity.
After that, you’ll see the next forecasted weather in 14 days. That’s why we have seven columns that represent the day and rows to represent the two-week weather forecast.
Lastly, within the table’s column, you’ll see an image representing the weather forecast for that day.
Here are the steps you should take to create this application.
Analyze the JSON results
We only need to analyze one item in the JSON result as the data structure is the same, and values will vary from day to day.
humidity: Array(2)
0: {observation_time: "2020-12-01T06:00:00Z", min: {…}}
1: {observation_time: "2020-11-30T21:00:00Z", max: {…}}
length: 2
__proto__: Array(0)
lat: 14.5708313
lon: 121.02040299999999
observation_time: {value: "2020-11-30"}
temp: Array(2)
0: {observation_time: "2020-11-30T22:00:00Z", min: {…}}
1: {observation_time: "2020-12-01T04:00:00Z", max: {…}}
length: 2
__proto__: Array(0)
weather_code: {value: "cloudy"}
As you can see, we have two entries within the humidity property and temperature property.
Based on the data, this is because it will give you the lowest and highest possible reading. Lastly, weather_code is the forecasted weather of the day.
Display weather information
function showFirstDetails(weatherInfo) {
const doc = document,
weatherCode = doc.querySelector('#weather_code'),
tempHigh = doc.querySelector('#tempHigh'),
tempLow = doc.querySelector('#tempLow'),
humidityPercentageHigh = doc.querySelector('#humidityPercentageHigh'),
humidityPercentageLow = doc.querySelector("#humidityPercentageLow"),
currentDateRequest = doc.querySelector('#currentDateRequest'),
weather_code_string = doc.querySelector("#weather_code_string");
let firstInfo = weatherInfo;
console.log(firstInfo);
if (firstInfo) {
weatherCode.classList.add(firstInfo.weather_code.value);
tempHigh.innerHTML = firstInfo.temp[1].max.value + "°" + firstInfo.temp[1].max.units;
tempLow.innerHTML = firstInfo.temp[0].min.value + "°" + firstInfo.temp[0].min.units;
humidityPercentageHigh.innerHTML = firstInfo.humidity[1].max.value + firstInfo.humidity[1].max.units;
humidityPercentageLow.innerHTML = firstInfo.humidity[0].min.value + firstInfo.humidity[0].min.units;
currentDateRequest.innerHTML = new Date(firstInfo.observation_time.value).toDateString();
weather_code_string.innerHTML = firstInfo.weather_code.value;
}
}
As you can see in the code snippet, we chose the first index of the collection to show within the header section of the widget, such as temperature, humidity min and max, and the weather forecast for that day.
The images used for the weather forecast came from ClimaCell’s GitHub repository.
Now, it’s good to put each weather code into a class equivalent to its image to present the image inside the widget.
Here’s how
.weather {
background-repeat: no-repeat;
background-position: center;
height: 50px;
width: 100px;
}
.freezing_rain_heavy {
background-image: url("/weather-code-icons-master/color/freezing_rain_heavy.svg");
}
.freezing_rain {
background-image: url("/weather-code-icons-master/color/freezing_rain.svg");
}
.freezing_rain_light {
background-image: url("/weather-code-icons-master/color/freezing_rain_light.svg");
}
.freezing_drizzle {
background-image: url("/weather-code-icons-master/color/freezing_drizzle.svg");
}
.ice_pellets_heavy {
background-image: url("/weather-code-icons-master/color/ice_pellets_heavy.svg");
}
.ice_pellets {
background-image: url("/weather-code-icons-master/color/ice_pellets.svg");
}
.ice_pellets_light {
background-image: url("/weather-code-icons-master/color/ice_pellets_light.svg");
}
.snow_heavy {
background-image: url("/weather-code-icons-master/color/snow_heavy.svg");
}
.snow {
background-image: url("/weather-code-icons-master/color/snow.svg");
}
.snow_light {
background-image: url("/weather-code-icons-master/color/snow_light.svg");
}
.flurries {
background-image: url("/weather-code-icons-master/color/flurries.svg");
}
.tstorm {
background-image: url("/weather-code-icons-master/color/tstorm.svg");
}
.rain_heavy {
background-image: url("/weather-code-icons-master/color/rain_heavy.svg");
}
.rain {
background-image: url("/weather-code-icons-master/color/rain.svg");
}
.rain_light {
background-image: url("/weather-code-icons-master/color/rain_light.svg");
}
.drizzle {
background-image: url("/weather-code-icons-master/color/drizzle.svg");
}
.fog_light {
background-image: url("/weather-code-icons-master/color/fog_light.svg");
}
.fog {
background-image: url("/weather-code-icons-master/color/fog.svg");
}
.cloudy {
background-image: url("/weather-code-icons-master/color/cloudy.svg");
}
.mostly_cloudy {
background-image: url("/weather-code-icons-master/color/mostly_cloudy.svg");
}
.partly_cloudy {
background-image: url("/weather-code-icons-master/color/partly_cloudy_day.svg");
}
.mostly_clear {
background-image: url("/weather-code-icons-master/color/mostly_clear_day.svg");
}
.clear {
background-image: url("/weather-code-icons-master/color/clear_day.svg");
}
The next and last step is showing the remaining forecasted days.
We iterated to the data that the API provided to us and put those data in a table to show the related weather codes via images.
See the code sample below.
function showDetails(weatherInfos) {
for (let counter = 1; counter < 8; counter++){
document.querySelector("#date" + (counter)).innerHTML =
showDays(new Date(weatherInfos[counter].observation_time.value).getDay());
document.querySelectorAll("#firstGroup tr td")[counter-1].classList.add(weatherInfos[counter].weather_code.value);
}
for (let counter2 = 8; counter2 < weatherInfos.length; counter2++) {
document.querySelector("#date" + (counter2)).innerHTML =
showDays(new Date(weatherInfos[counter2].observation_time.value).getDay());
document.querySelectorAll("#secondGroup tr td")[counter2 - 8].classList.add(weatherInfos[counter2].weather_code.value);
}
}
And for us to visualize the HTML template that we have, see the sample code below.
<div class="container">
<div class="topContent">
<div class="topLeft">
<div id="weather_code" class="weather">
<span>
<small class="small" id="weather_code_string"></small>
</span>
</div>
</div>
<div class="topRight">
<div>
High: <span id="tempHigh"></span>
Low: <span id="tempLow"></span>
</div>
<div>Humidity
<span id="humidityPercentageHigh"></span>
<span id="humidityPercentageLow"></span>
</div>
<div>Date: <span id="currentDateRequest"></span>
</div>
</div>
</div>
<div class="bottomContent">
<table id="firstGroup">
<thead>
<tr>
<th id="date1"></th>
<th id="date2"></th>
<th id="date3"></th>
<th id="date4"></th>
<th id="date5"></th>
<th id="date6"></th>
<th id="date7"></th>
</tr>
</thead>
<tbody>
<tr>
<td class="weather"></td>
<td class="weather"></td>
<td class="weather"></td>
<td class="weather"></td>
<td class="weather"></td>
<td class="weather"></td>
<td class="weather"></td>
</tr>
</tbody>
</table>
<table id="secondGroup">
<thead>
<tr>
<th id="date8"></th>
<th id="date9"></th>
<th id="date10"></th>
<th id="date11"></th>
<th id="date12"></th>
<th id="date13"></th>
<th id="date14"></th>
</tr>
</thead>
<tbody>
<tr>
<td class="weather"></td>
<td class="weather"></td>
<td class="weather"></td>
<td class="weather"></td>
<td class="weather"></td>
<td class="weather"></td>
<td class="weather"></td>
</tr>
</tbody>
</table>
</div>
</div>
You can access the source code of this application here.
Summary
We have now seen how to get started with ClimaCell's weather API calls using the daily API. We have shown the following: get your API key, set your current location, how to make an API request, and see the results in JSON format. After we got the basic knowledge of integrating JavaScript with ClimaCell's API, we created a simple weather application to understand the data we have received and present it to a user interface.
Lastly, in my opinion, using ClimaCell's weather API is straightforward, and their documentation is easy to understand.
I hope you have enjoyed this article, as much as I have enjoyed writing it. Stay tuned for more. Until next time, happy programming!