Weather app project: How to connect Weather API with HTML5 Geolocation?

Weather app project: How to connect Weather API with HTML5 Geolocation?
0

#1

I’m a bit lost, and I was hoping someone could point me in the right direction. I don’t want to just copy someone’s code without explaining it, but I’m not sure what step to take from here.

I’ve managed to get the weather API to work with the HTML5 geolocation API, but it displays in JSON format. How do I get it to simply take this data and display it as: city, country, temperature on the webpage? My code below:

var showLocation = document.getElementById("storeWeather");

$(document).ready(function() {

    // get the user's longitude and latitude using html5 geolocation
    function userLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPoints);
        } else {
            showLocation.innerHTML = "Your browser does not support this feature.";
        }

        function showPoints(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            showLocation.innerHTML = "Latitude: " + latitude +
                "<br> Longitude: " + longitude;

            // AJAX request
            var api = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=eec551a3788ea51493994e5edfb48781";
            $.getJSON(api, function(json) {
                var rawJson = JSON.stringify(json);
                var json = JSON.parse(rawJson);
                $("#storeWeather").html(JSON.stringify(json));
            });
        }
    }
    userLocation();
});

#2

The following statement in your code:

$.getJSON(api, function(json) {

allows you to access a JSON object. The variable json has the object information in t. Put a console.log(json) on the first line inside this function so you can see the structure in the console. If you can not remember how to access data within a nest object, you should review the following FCC challenge:

Also, you do not need these 3 lines, because the variable json has everything you need:

 var rawJson = JSON.stringify(json);
 var json = JSON.parse(rawJson);
 $("#storeWeather").html(JSON.stringify(json));