I am currently doing projects in freecodecamp.com
to brush up on my javascript skills and just finished a weather report widget. It does the following:
- Gets api from
openweathermap.org
and displays the weather based on user's latitude and longitude - Displays the city, weather description and wind speed
- Can toggle between celsius and ferenheit
I want to become a better javascript developer and use best-practice tools and design patterns. Therefore, I would kindly ask if anyone has design pattern suggestions for making my code more efficient, less redundant, and more functional.
Also, the console displays getCurrentPosition()
and watchPosition()
are deprecated on insecure origins why is this, and is there an alternative for getting the user's position from directly from the browser?
The following is my javascript code:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=eee5ab7fffb62d126756d9b810ee1875", function(data) {
var temp = JSON.stringify(data.main.temp);
//Convert to Ferenheit
var temp2 = temp * 9 / 5 - 459.67;
//Round to 2nd decimal place
var temp3 = Math.round(temp2 * 10) / 10;
//Display
$('#temperature').html(temp3 + " F");
//Description
var description = data.weather[0].description;
//Wind speed
var wind = JSON.stringify(data.wind.speed);
//HTML disaply
$(".report").html("<li>" + data.name + "</li>" + "<li>" + description + "</li><li>" + wind + " knots</li>");
//Toggle Logic
$('#celsius').on('click', function() {
var celsius = temp - 273.15;
var celsius2 = Math.round(celsius * 10) / 10;
$('#temperature').html(celsius2 + " C");
$('#celsius').removeClass('btn-default').addClass('btn-primary');
$('#ferenheit').removeClass('btn-primary').addClass('btn-default');
});
$('#ferenheit').on('click', function() {
var temp = JSON.stringify(data.main.temp);
var temp2 = temp * 9 / 5 - 459.67;
var temp3 = Math.round(temp2 * 10) / 10;
$('#temperature').html(temp3 + " F");
$('#ferenheit').removeClass('btn-default').addClass('btn-primary');
$('#celsius').removeClass('btn-primary').addClass('btn-default');
});
//Icons logic
if (description == "broken clouds" || "scattered clouds") {
$("i").addClass("wi-cloudy");
} else if (description == "few clouds") {
$("i").addClass("wi-cloud");
} else if (description == "clear sky") {
$("i").addClass("wi-day-sunny");
} else if (description == "shower rain" || "rain") {
$("i").addClass("wi-rain");
} else if (description == "thunderstorm") {
$("i").addClass("wi-storm-showers");
} else if (description == "snow") {
$("i").addClass("wi-snowy");
} else if (description == "mist") {
$("i").addClass("wi-dust");
};
});
});
}
You can find the rest of my code in the gist here.
description == "broken clouds" || "scattered clouds"
? \$\endgroup\$