when am i try to pass link variable in request.open() i get undefined, but when i print it in console it get printed. so my question is why it shows me undefined? and is there any why to improve my code?
window.onload = loadData;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
document.getElementById('demo').innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
const loc = "https://fcc-weather-api.glitch.me/api/current?lat="+position.coords.latitude+"&lon="+position.coords.longitude;
console.log(loc);
}
function loadData() {
const request = new XMLHttpRequest();
const link = getLocation();
request.open('GET', link, true); // here it pass undefined instead of link.
request.onload = function() {
if(this.status === 200) {
const data = JSON.parse(this.responseText);
document.querySelector('.icon').innerHTML = `<img src=${data.weather[0].icon} alt="Weather Icon" />`;
document.querySelector('.icon_name').innerHTML = `${data.weather[0].main} `;
document.querySelector('.num').innerHTML = `${data.main.temp}`;
document.querySelector('.loc').innerHTML = `${data.name}`+", " +`${data.sys['country']}`;
}
}
request.send();
}
I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.
Yeah, showPosition is just assigning a variable, the function just returns undefined. return "https://fcc-weather-api.glitch.me/ap... rather than const loc = "https://fcc-weather-api.glitch.me/ap...
And getting geolocation is an asynchronous operation: even if you make it return the correct URL, link is still going to be undefined in request.open('GET', link, true);, because that function isn’t going to sit and wait for the coordinates to come back from the system. You need the AJAX request to fire in the geolocation callback, ie once the coordinates have been established.
Your logic is a bit off. When the page loads, you should be calling getLocation and not loadData. Why? Because loadData assumes you already have have a URL for the weather API. You try to call getLocation in the request.open, but since the navigator.geolocation.getCurrentPosition is asynchronous, it does not wait until a response comes back to it before proceeding, so the call to getLocation just returns undefined.
Your loadData function needs a parameter where you can pass in the weather API url, then inside your showPosition function you can call loadData with the applicable url instead of showPosition returning a url as you are currently doing.