Making the weather app, need a little bit of help

Hello guys. I am currently making the weather APP, and having some issues with the URL.

var lat;
var long;

function getLocation() {
navigator.geolocation.getCurrentPosition(showPosition);
}

getLocation();

function showPosition(position) {
lat = position.coords.latitude;
long = position.coords.longitude;
}

var xmlhttp = new XMLHttpRequest(),
method = ‘GET’,
url = ‘https://fcc-weather-api.glitch.me/api/current?lat=’ + lat + ‘&lon=’ + long;

xmlhttp.open(method, url, true);
xmlhttp.onload = function test() {
var response = JSON.parse(this.responseText);
var weather = response.weather[0].main;
var temperature = response.main.temp;
var country = response.sys.country;
var city = response.name;
console.log(weather);
console.log(temperature);
console.log(city);
console.log(country);
};

xmlhttp.send();

This is my code. When using the example request, it worked very well. However, when I try to do this URL with the + lat + long part, it returns the URL correctly, except for the part of lat and long, which are “undefined” in the URL. Anyone who can help me understand why they are undefined? Console-logging lat and long individually returns the proper data, so why does it not work in the url?

Appreciate any help :slight_smile:

I think it could be to do with scope of your lat and long variables. They might only be valid in the showPosition() function and then they go out of scope.

This is probably bad coding practice, but in my project, literally everything is inside the geolocation getCurrentPosition() function and it’s working for me!

1 Like