0

I've a problem with the following script:

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

// Start of geolocation block

function theCallback(position) {
        //console.log(position.coords);
        crd = position.coords;
}

function errorHandler(err) {
            if(err.code == 1) {
               alert("Error: Access is denied!");
            }

            else if( err.code == 2) {
               alert("Error: Position is unavailable!");
            }
}

function getLocation(callback)
{   
    if(navigator.geolocation) {
        // timeout at 60000 milliseconds (60 seconds)
        var options = {timeout:60000};
        navigator.geolocation.watchPosition(theCallback, errorHandler, options);
    }
    else {
        alert('W3C Geolocation API is not available');
    }
}

// End of geolocation block

function weatherReq(crd) {
    var location = "lat=" + lat + "&" + "lon=" + lon;
    var appId = "---THEAPIKEY---"
    var request = "http://api.openweathermap.org/data/2.5/weather?" + location + "&APPID=" + appId;
    var weatherReq = new XMLHttpRequest();
    weatherReq.open("GET", request, false);
    console.log(request);
    weatherReq.send();
    if (weatherReq.status === 200) {
        respJSON = JSON.parse(weatherReq.responseText);
        return 0;
    }
    else {
        alert("Some error occurred during the request");
        return 2;
    }
}

function main () {

    getLocation(function(data) {
        lat = data.latitude;
        lon = data.longitude;
        lat -= (lat % 1);
        lon -= (lon % 1);
        console.log(crd + " " + lat + " " + lon);
        weatherReq(lat, lon);
        console.log(respJSON.id);
    });

    var randomColor = getRandomColor();

    $("body").css("transition", "background-color 1s ease");

    $("body").css("background-color", randomColor);

}




$(document).ready(main);

It doesn't work. The parameter "data" (line 61) doesn't get a value nor the variable "crd" (line 14).

I don't understand if the problem is due to the asynchronous nature of the geolocation or by the variable scope.

By the way, if I try to declare the variable in main, console tells that it's undefined.

Thanks in advance.

Alby11
  • 607
  • 1
  • 7
  • 15
  • 1
    getCurrentPos, which sets lat & lon, is only called when navigator.geolocation.getCurrentPosition. So it hasn't been called yet when weatherReq is called. You could create a callback function for navigator.geolocation.getCurrentPosition which calls getCurrentPos then weatherReq. – xrgb Mar 31 '16 at 11:39
  • Thank you @xrgb!! I'm a total newbie!! Would you please show me how? – Alby11 Mar 31 '16 at 11:42
  • 1
    Check out the question and discussions mentioned above! – xrgb Mar 31 '16 at 12:44

0 Answers0