How to get the current weather using the Dark Sky API

Every front-end developer has to be comfortable working with several API’s for the sake of becoming a competent coder. Unless you are also a back-end developer, to know how the API calls work and how the data is received is key to effectively manipulate the data and implement it in your web app. That is why FreeCodeCamp has a good portion of its front-end certification focused on working with API services through JavaScript. At the moment, I am working on my TwitchTV project which needs to check either the streamers are online, provide a link to their channel and describe what are they are streaming. All using the Twitch API.
TIP: Check this API directory from ProgrammableWeb to have an idea of how many API’s are present on the web.
So, you are reading this article because you are either a camper trying to finish your project or you need Dark Sky to implement some cool weather information in your app. I will describe the necessary steps to use the Dark Sky API.
Setting up a Dark Sky developer account
First of all, you will have to create a Dark Sky Account. You can use their API for free as long as you don’t overcome more than 1000 of forecasts calls per day. After logging in into your account you will be able to create your secret key which is what enables you to connect with their API. Without this secret key you will not be able to get any data.

I encourage you to spend some time reading the documentation before implementing your request. In my case, I obtained solely the current weather forecast. However, you can go further and get the weather hourly and also daily.
Ask permission to get the user’s browser location
Following your “quick” look at the documentation you can finally start coding. The first thing you have to implement is checking if the browser has geolocation available and if so, ask the user to access their browser location in order to obtain their latitude and longitude.
NOTE: One problem you can face is in-app browsers, where the geolocation is not supported.
Check if the browser supports geolocation
if (!navigator.geolocation){ alert(“Geolocation is not supported by this browser!”); }Ask the user if you can obtain his location
//This will make appear a pop up asking for permission navigator.geolocation.getCurrentPosition(showPosition, error); //In case the permission is granted
function showPosition(position) {
a_lat = position.coords.latitude;
a_long = position.coords.longitude;
} //In case the permission is denied
function error() {
alert(“Unable to retrieve your location! Allow the browser to track your location!”);
}
Use latitude and longitude to acquire the city name and country name with Google Maps API
I decided to try the Google Maps API to obtain the city and country name with the longitude and latitude obtained in the previous step. Here it is how I did it.
Google Maps required url
var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat + "," + long;jQuery method to obtain the data through json
$.getJSON(url, function(data) {
var arr_address_comp = data.results[0].address_components;
arr_address_comp.forEach(function(val) {
if(val.types[0] === "locality" ){
cityName = val.long_name;
}
if(val.types[0] === "country" ){
countryCode = val.short_name;
countryName = val.long_name;
}
});
//set your tag element where you will describethe location $('#weather-location').text(cityName + ", " + countryName);
});If the request is successful, the function inside .getJSON() is processed and the country name and city name are extracted.
Process the Dark Sky request
Now you are all set to execute the DarkSky request. You will need the following parameters in the URL.
- apiKey: your DarkSky secret key
- exclude: in this parameter you can tell the API to ignore data you don’t need in your app. This reduces the response time.
- units: type of measure you prefer
- url: link to the API
- lat: latitude
- lon: longitude
This time, instead of .getJSON() I will show you a jQuery .ajax() method to execute a API request.
function getWeatherData(lat, long){
var apiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
var exclude = "?exclude=minutely,hourly,daily,alerts,flags";
var unit = "?units=si";
var url = "https://api.darksky.net/forecast/" + apiKey + "/" + lat + "," + long + exclude + unit; //get darksky api data
$.ajax({
url: url,
dataType: "jsonp",
success: function (weatherData) {
//icon information (explained after)
var icon = weatherData.currently.icon;
//weather description
var description = weatherData.currently.summary;
//temperature
var temperature = weatherData.currently.temperature;
}
});
}
The success parameter indicates what to do if there is a successful response of the ajax request. Taking a look at my example and the API documentation you will see where do I get the data.
Populate the weather data
Once you got all the information you need, its time too fill in the “blanks” of your web app. In my project I used the following fields (see image below):
weatherData.currently.summary: This field simply describes the current weather
$('#weather-description').text(weatherData.currently.summary);weatherData.currently.temperature: Contains the current temperature. Check if you have to do a conversion before putting in your page.
$('#weather-value').val(weatherData.currently.temperature);weatherData.currently.icon: An additional parameter that DarkSky provides to help the developers implement their dynamic weather icons. I used Skycons to set up animated weather icons as you can see in my Weather App.
To use Skycons, you have to include their library in your code. Then, just follow the example provided on their website. You will end up with some JavaScript code like this:
//add to skyicons the weather information skycons.add(document.getElementById("icon"), weatherData.currently.icon); //start animation skycons.play();
Other features
Temperature conversion and setting up a different background image depending on the weather were other features I implemented. You can see what I have done below.
// Functions used to apply conversions
function toCelsius(f) {
return Math.round((5/9) * (f-32));
} function toFahrenheit(c){
return Math.round(c * 9 / 5 + 32);
}//JavaScript object containing the icon information
//and the respective image url
var listImages = {
"clear-day": "your-image-url",
"clear-night": "your-image-url",
"foggy": "your-image-url",
...
};//funciton that sets the background image depending on the parameter icon provided
function setBackgroundImg(description){
$('body').fadeTo('slow', 0.3, function(){
$('html').css('background-image',"url("+listImages[description]+")");
$('.containerBlock').css('visibility',"visible");
}).delay( 500 ).fadeTo('slow', 1);
}
With all this information you should be able to implement your own weather app easily. Note that I highlighted only the relevant code to use the Dark Sky API. If you want to see more feel free to check my Weather App project or even better, search through the FreeCodeCamp forum to get help from other campers. It is where I go when I am stuck in a challenge.
Its all about cooperation
I hope this tutorial helped you in some way achieving what you were looking for. Feel free to get in touch if you want to know more or need some help. I am just like you, a learner trying to improve everyday. I became a camper in February 2017 and I have now 4 projects left to obtain the front-end certification. I have an enormous respect for Quincy Larson for the project he created and have been a follower ever since I found FreeCodeCamp. I hope I can give something back to the community in a near future.
NOTE: I did not get a job yet as a web developer since I came to Canada. Also, it is harder to get that job because I am also taking my bachelor in Computer Science, leaving me with no time to be a full-time employee in a company.
If you don’t know, this is just my second blog post, if you are curious what I am going to blog about check my first post “My first post, after a long period of time procrastinating!”
Try and fail, as many times as required, but don’t stop until you get out of the loop. That is where the success can be found.
Originally published at tiagovalverde.com on July 23, 2017.
