Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

. Hello, I'm trying to complete this tutorial but they have left out some key parts in their instructions. I've figured out some of what was missing but I can't plug in flickr images that are returned by the Photo Search API as a background. I keep getting ReferenceError: jsonFlickrApi is not defined as a console error despite the fact that I can see the data I need. If anyone could explain what I'm doing wrong I would appreciate it greatly, thanks!

JS:

document.onreadystatechange = function(){
    if(document.readyState === "interactive"){
        var weatherData = {
            city:               document.querySelector("#city"),
            weather:            document.querySelector("#weather"),
            temperature:        document.querySelector("#temperature"),
            temperatureValue:   0,
            units:              "°F"
        };

        function getLocationAndWeather(){
            if (window.XMLHttpRequest){
                var xhr = new XMLHttpRequest();
                xhr.addEventListener("load", function() {
                    console.log("Processing weather info...");
                    var response = JSON.parse(xhr.responseText);

                    console.log(response);
                    var position = {
                        latitude:   response.latitude,
                        longitude:  response.longitude
                    };
                    var cityName = response.city;
                    if(cityName =="Earth"){
                        /*IP-based location detection failed.*/
                        /*Ask user where he or she lives*/
                        getWeatherForLocation();
                    } else {
                    var weatherSimpleDescription    = response.weather.simple;
                    var weatherDescription          = response.weather.description;
                    var weatherTemperature          = Math.round(response.weather.temperature * 9/5 + 32);

                    weatherData.temperatureValue = weatherTemperature;

                    loadBackground(position.latitude, position.longitude, weatherSimpleDescription);

                    weatherData.city.innerHTML          = cityName;
                    weatherData.weather.innerHTML       = ", " + weatherDescription;
                    weatherData.temperature.innerHTML   = weatherTemperature + weatherData.units;
                    console.log("Finished proessing and displaying weather info...");

                    }
                }, false);

                xhr.addEventListener("error", function(err){
                    alert("Could not complete the request");
                }, false);

                xhr.open("GET", "https://fourtonfish.com/tutorials/weather-web-app/getlocationandweather.php?owapikey=ab2497c49afeabeff924fb4bd2288ee5&units=metric", true);
                xhr.send();
                console.log("Requesting weather info...");
            } else { 
                alert("Unable to fetch location and weather data.");
            }
        }

        function getWeatherForLocation(){
            var location = prompt("Your location could not be detected automatically, can you tell me where you live?");
            if (location != null){
                document.querySelector("body").style.backgroundImage = "url('https://fourtonfish.com/tutorials/weather-web-app/images/default.jpg')";
                document.querySelector("#image-source").setAttribute("href", "https://www.flickr.com/photos/superfamous/310185523/sizes/o/");

                var xhr = new XMLHttpRequest();
                xhr.addEventListener("load", function() {
                    var response = JSON.parse(xhr.responseText);

                    console.log(response);
                    var position = {
                        latitude: response.latitude,
                        longitude: response.longitude
                    };
                    var lat = response.latitude;
                    var lon = response.longitude;
                    var cityName = response.city;

                    var weatherSimpleDescription = response.weather.simple;
                    var weatherDescription = response.weather.description;
                    var weatherTemperature = Math.round(response.weather.temperature);
                    weatherData.temperatureValue = weatherTemperature;

                    weatherData.city.innerHTML = cityName;
                    weatherData.weather.innerHTML =  ", " + weatherDescription;
                    weatherData.temperature.innerHTML = weatherTemperature + weatherData.units; 

                }, false);

                xhr.addEventListener("error", function(err){
                    alert("Could not complete the request");
                }, false);



                xhr.open("GET", "https://fourtonfish.com/tutorials/weather-web-app/getweatherforlocation.php?owapikey=45713cc0d54c4bfa1c7efbbdbd1c6c2b&units=metric&location=" + location, true);
                xhr.send();
            }
            else{
                alert("Unable to fetch the location and weather data.");
            }                       
        }

        function loadBackground(lat, lon, weatherTag) {
            var script_element = document.createElement('script');

            script_element.src = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=0677de6a559772c8cb27dd22219dfa0c&lat=" + lat + "&lon=" + lon + "&accuracy=1&tags=" + weatherTag + "&sort=relevance&extras=url_l&format=json";

            document.getElementsByTagName('head')[0].appendChild(script_element);
        }

        function jsonFlickrApi(data){
                if (data.photos.pages > 0){
                    var photo = data.photos.photo[0];
                    console.log("Photo data: " + photo);
                    document.querySelector("weather-web-app").style.backgroundImage = "url('" + photo.url_l + "')";
                    document.querySelector("#image-source").setAttribute("href", "http://www.flickr.com/photos/" + photo.owner + "/" + photo.id);
                }
                else{
                    document.querySelector("weather-web-app").style.backgroundImage = "url('https://fourtonfish.com/tutorials/weather-web-app/images/default.jpg')";
                    document.querySelector("#image-source").setAttribute("href", "https://www.flickr.com/photos/superfamous/310185523/sizes/o/");
                }
            }

            getLocationAndWeather();

        }
}
share|improve this question
1  
What line is giving you the reference error? Since you don't appear to ever call jsonFlickrApi in the code you have posted. – Matt Burland Dec 17 '14 at 14:52
    
Good question. The location for the error is "?method...at=json(line 1)". Not sure if that helps. – mario Dec 17 '14 at 15:04
    
And I tried adding "jsonFlickrApi(photos);" after calling getLocationAndWeather() but it is still saying jsonFlickrApi is undefined despite the fact that I can see the values for photo in the head when I inspect the page. Thanks again! – mario Dec 17 '14 at 15:15

2 Answers 2

First, you have a typo in that line:

script_element.src = "...&accuracy=1" +  + &sort=relevance...";

Second, the Flickr api using JSONP, as I see, which requires the callback function to be defined on the receiver side. Since you put this function into the listener and into condition it's gonna be undefined.

Put it outside:

document.onreadystatechange = function() {
    ...
}
function jsonFlickrApi() {...}
share|improve this answer
    
That helped but now I'm getting an error on my querySelector because it is attempting to select something that doesn't yet exist because it is out of the onreadystatechange. – mario Dec 17 '14 at 17:07
1  
Can you share the html as well you use for this script? :) A plunker example would be great to debug this :) – draconteus Dec 18 '14 at 10:49
    
<div id="weather-web-app"> <section> <h1 id="city">Weather Web App</h1> <p> <span id="temperature"> </span> <span id="weather"> Current temperature and weather conditions </span> </p> </section> </div> – mario Dec 18 '14 at 14:13
    
I actually got the undefined bug worked out right before I had to quit yesterday, but thanks! On to the next bug in the code! lol. – mario Dec 18 '14 at 14:13

Okay, realized what it was.

Flikr didn't like

script_element.src = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=0677de6a559772c8cb27dd22219dfa0c&lat=" + lat + "&lon=" + lon + "&accuracy=1&tags=" + weatherTag + "&sort=relevance&extras=url_l&format=json";

Specifically it didn't like my weatherTag variable.

so

script_element.src = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=0677de6a559772c8cb27dd22219dfa0c&lat=" + lat + "&lon=" + lon + "&accuracy=1" +  + "&sort=relevance&extras=url_l&format=json";

instead worked fine.

Thanks!

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.