Show the Local Weather - Almost Got It

Show the Local Weather - Almost Got It
0

#1

Hello,

This is my javascript file, and my index page just has some paragraphs with ids. I have the data, and it’s populating. My question is how can I refactor this, is it best practice to do everything in the success property like this? I figured since I have the basic of what needs to be done there, maybe I can refactor. Looking for insight.

$(document).ready(function () {

var init = {
    api: 'http://api.openweathermap.org/data/2.5/weather?',
    apiKey: ''
};

if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        var yourLatitude = position.coords.latitude;
        var yourlongitude = position.coords.longitude;

        $.ajax({
            url: init.api + 'lat=' + yourLatitude + '&lon=' + yourlongitude + '&appid=' + init.apiKey,
            dataType: 'jsonp',
            success: function(results){

                var city = results.name;
                var overcast = results.weather[0].main;
                var tempature = convertToC;


                $('#city').text(city);
                $('#overcast').text(overcast);
                $('#tempature').text(tempature);

                function convertToC() {
                    return results.main.temp - 273.15;
                }

                console.log(results);
            }
        });

    });
} else {
    console.log('Failed');
}

});

#2

You’ll want some better error handling. Right below the success property, you can add another function called error, which receives an error object.

$.ajax({
  url: '',
  dataType: 'jsonp',
  success: function(results) { /* ... */ },
  error: function(error) { /* ... */ }
})

Make sure your error handling lets the user know when something’s gone wrong. It should populate the page with information that tells the user what’s wrong, and maybe even how to fix it. In this same vein, your else clause at the bottom of the function should do the same. I believe that code will only be reached if the user’s browser doesn’t support geolocation, so tell the stinking luddite to update their browser. There’s a different error that pops up when the user refuses geolocation. Try searching the documentation for more info on that. It’ll be good exercise!