"weather is not defined" error when working with openwethermap API - javascript

I'm somewhat new to working with API's using vanilla JavaScript and I keep running into this error when trying to access the "description" within the "weather object". The console keeps reading "weather is not defined". I'm using the open weather map API. In theory I should be able to retrieve using data.current.weather.description. but that doesn't work, along with the other variations I've tried. Here is my current code.
window.addEventListener("load", () => {
let long;
let lat;
let temperatureDescription = document.querySelector(
".temperature-description"
);
let temperatureDegree = document.querySelector(".temperature-degree");
let locationTimezone = document.querySelector(".location-timezone");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
long = position.coords.longitude;
lat = position.coords.latitude;
const proxy = "https://cors-anywhere.herokuapp.com/";
const api = `${proxy}https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${long}&
exclude=hourly,daily&appid=da5463709c92ab1860d3a81037565c6e`;
fetch(api)
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
const {
temp,
weather: { description },
} = data.current;
//Set DOM Elements from the API
let kelvinToCelsius = temp - 273.15;
temperatureDegree.textContent = kelvinToCelsius.toFixed(0);
temperatureDescription.textContent = description;
locationTimezone.textContent = data.timezone;
});
});
} else {
}
});
If anyone has ran into this issue and solved, it would be much appreciated if you filled me in.

Related

how to connect pagespeed API to Google sheet?

I am trying to get create a dashboard on google data studio from the pageSpeed API.
I want to get data on google sheet schedule everyday and after it will update data on google data studio.
I found some codes on official documentation.
It needs some connection with google sheet.
Please fix the below code as per google sheet for website.com.
<script>
function run() {
const url = setUpQuery();
fetch(url)
.then(response => response.json())
.then(json => {
// See https://developers.google.com/speed/docs/insights/v5/reference/pagespeedapi/runpagespeed#response
// to learn more about each of the properties in the response object.
showInitialContent(json.id);
const cruxMetrics = {
"First Contentful Paint": json.loadingExperience.metrics.FIRST_CONTENTFUL_PAINT_MS.category,
"First Input Delay": json.loadingExperience.metrics.FIRST_INPUT_DELAY_MS.category
};
showCruxContent(cruxMetrics);
const lighthouse = json.lighthouseResult;
const lighthouseMetrics = {
'First Contentful Paint': lighthouse.audits['first-contentful-paint'].displayValue,
'Speed Index': lighthouse.audits['speed-index'].displayValue,
'Time To Interactive': lighthouse.audits['interactive'].displayValue,
'First Meaningful Paint': lighthouse.audits['first-meaningful-paint'].displayValue,
'First CPU Idle': lighthouse.audits['first-cpu-idle'].displayValue,
'Estimated Input Latency': lighthouse.audits['estimated-input-latency'].displayValue
};
showLighthouseContent(lighthouseMetrics);
});
}
function setUpQuery() {
const api = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed';
const parameters = {
url: encodeURIComponent('website.com')
};
let query = `${api}?`;
for (key in parameters) {
query += `${key}=${parameters[key]}`;
}
return query;
}
function showInitialContent(id) {
document.body.innerHTML = '';
const title = document.createElement('h1');
title.textContent = 'PageSpeed Insights API Demo';
document.body.appendChild(title);
const page = document.createElement('p');
page.textContent = `Page tested: ${id}`;
document.body.appendChild(page);
}
function showCruxContent(cruxMetrics) {
const cruxHeader = document.createElement('h2');
cruxHeader.textContent = "Chrome User Experience Report Results";
document.body.appendChild(cruxHeader);
for (key in cruxMetrics) {
const p = document.createElement('p');
p.textContent = `${key}: ${cruxMetrics[key]}`;
document.body.appendChild(p);
}
}
function showLighthouseContent(lighthouseMetrics) {
const lighthouseHeader = document.createElement('h2');
lighthouseHeader.textContent = "Lighthouse Results";
document.body.appendChild(lighthouseHeader);
for (key in lighthouseMetrics) {
const p = document.createElement('p');
p.textContent = `${key}: ${lighthouseMetrics[key]}`;
document.body.appendChild(p);
}
}
run();
</script>
some similar codes but i cant find the source of the codes
youtube video link

Having trouble console.log anything from this API, we're not allowed to use JQuery or Bootstrap, so I have to use fetch and bulma

so I've been having trouble trying to get anything to console.log from this API, the most I can get is a null or undefined return. I've tried just the base statement from the API company, and the code snippet runs for them but for some reason won't even return a console.log for me. not sure if it's a problem on their end or mine because it seems to run fine on their website. also as I said in the title, I have to use fetch
EDIT: I'm in coding school right now so I'm pretty new to all of this
EDIT: the dashboard shows that the API is being called, so why am I not getting any responses?
EDIT: I figured it out, the API wasn't working
// global variables
var countryInput = document.querySelector("#ipt-country");
var submitButton = document.querySelector("#submit-btn");
var currencyDisplay = document.querySelector("#currency-display");
// country currency array codes
var countryCurrencyArray =[ list off all countries with iso code for currency goes here, not going to list it bc its 270 lines long
];
// begins exchange rate function
function getExchangeRate() {
// grab data attribute
var countrySearch = countryInput.value.toLowerCase().trim();
var currencyUSA = "USD";
var countryCurrency = "AUD";
// var countryCurrency = countryInput.value.countryCurrencyArray[i];
// if else errors
if (countrySearch.length < 1) {
return(null);
} else {
var countryConversion = countryCurrencyArray.find(
(element) => element.name === countrySearch)
}
if (countryConversion === void 0) {
return(null);
} else {
var countryCurrency = countryConversion.code;
}
// fetch API to change currency rate from American Dollar (USD) to selected currency
fetch(
'https://currency-converter5.p.rapidapi.com/currency/convert?' +
'&from=' + currencyUSA +
'&to=' + countryCurrency +
'&amount=1',
{
"method": "GET",
"headers": {
"x-rapidapi-host": "currency-converter5.p.rapidapi.com",
"x-rapidapi-key": "API-KEY"
},
}).then(response => {
console.log(response);
})
.then(function(response) {
response.json().then(function(data){
for (i=0; i < data.response.countryCurrency.length; i++) {
var exchangeMoney = document.createElement("div");
exchangeMoney.classList.add(
"is-flex-mobile",
"column",
"has-text-centered",
"is-justify-content-space-evenly"
);
var exchangeOutput = document.createElement("div");
exchangeRateOutput.classList.add("level-item");
exchangeRateOutput.innerText = data.response.countryCurrency[i].code;
exchangeRateMoney.appendChild(exchangeOutput);
console.log(exchangeOutput);
}
});
}).catch(err => {
console.error('Request Failed', err);
});
}
getExchangeRate();
console.log(getExchangeRate());
submitButton.addEventListener("click", getExchangeRate);

JavaScript issue with global variable assignment

I'm trying to create a weather widget using below code snippets. However, the global variables longitude and latitude values are not getting updated in the success function. I have tried all the combinations of globalThis and window objects but yet not been able to resolve the issue.
setInterval(showWeather, 900000);
setTimeout(showWeather,1000)
function showWeather(){
var appid = "API_KEY_FOR_OPENWEATHERMAP";
var latitude = 0;
var longitude = 0;
function success(position){
window.latitude = position.coords.latitude;
window.longitude = position.coords.longitude;
}
function error(){
console.log('Some error occurred while retrieving your device location! Hence showing the default location weather!')
}
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(success, error);
}else{
console.log("Your device doesn't support geolcation tracking! Hence showing the default location weather!")
}
async function fetchWeather(){
var url = `https://api.openweathermap.org/data/2.5/weather?lat=${window.latitude}&lon=${window.longitude}&appid=${appid}&units=metric`
const response = await fetch(url);
data = response.json();
return data
}
fetchWeather().then(response=>{
const icon = response.weather[0].icon;
document.getElementById("city").innerHTML = response.name;
document.getElementById("temp").innerHTML = response.main.temp + "°";
url = `https://openweathermap.org/img/w/${icon}.png`;
document.getElementById("wicon").src = url;
})
}
<h5 id="city">User Location</h5>
<div>
<img id="wicon" src="https://openweathermap.org/img/w/01d.png" alt="Weather icon">
<strong id="temp">Temperature°</strong>
</div>
getCurrentPosition() is asynchronous, but you're not waiting for it to finish before using the results. You should call fetchWeather() from the success() function, since that's called when getCurrentPosition() finishes.
There's no need to use global variables for latitude and longitude. Pass them as arguments to fetchWeather().
setInterval(showWeather, 900000);
setTimeout(showWeather, 1000)
function showWeather() {
var appid = "API_KEY_FOR_OPENWEATHERMAP";
function success(position) {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
fetchWeather(latitude, longitude).then(response => {
const icon = response.weather[0].icon;
document.getElementById("city").innerHTML = response.name;
document.getElementById("temp").innerHTML = response.main.temp + "°";
url = `https://openweathermap.org/img/w/${icon}.png`;
document.getElementById("wicon").src = url;
})
}
function error() {
console.log('Some error occurred while retrieving your device location! Hence showing the default location weather!')
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
console.log("Your device doesn't support geolcation tracking! Hence showing the default location weather!")
}
async function fetchWeather(latitude, longitude) {
var url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${appid}&units=metric`
const response = await fetch(url);
data = response.json();
return data
}
}
<h5 id="city">User Location</h5>
<div>
<img id="wicon" src="https://openweathermap.org/img/w/01d.png" alt="Weather icon">
<strong id="temp">Temperature°</strong>
</div>

geolocation keeps on asking for permission

I was testing geolocation API and found if I refresh my page, the page keeps on asking for permission, so I saved my coordinate data to local storage but it doesn't works! Is there any way to give permission only once???
const COORDINATION = "coords";
function saveCords(coordsOBJ){
localStorage.setItem(COORDINATION,JSON.stringify(coordsOBJ));
}
function handleGeoError(position){
console.log("Cant find position");
}
function handleGeoSuccess(position){
// console.log(position);
const latitude = position.coords.latitude;
console.log(latitude);
const longitude = position.coords.longitude;
const coordsOBJ = {
latitude,//latitude = latitude,
longitude//longitude = longitude
}
saveCords(coordsOBJ);
}
function askForCoords(){
navigator.geolocation.getCurrentPosition(handleGeoSuccess,handleGeoError);
}
function loadCoordinate(){
const loadedCords = localStorage.getItem("COORDINATION");
if(loadedCords === null)
{
askForCoords();
}
}
function init(){
loadCoordinate();
}
It looks like there is a typo in your code, whereby you've added quotes to COORDINATION but it's a varible not a string.
Try changing:
const loadedCords = localStorage.getItem("COORDINATION");
To:
const loadedCords = localStorage.getItem(COORDINATION);

Uncaught (in promise) TypeError: Cannot set property 'textContent' of null

this the file, and it's saying
Uncaught (in promise) TypeError: Cannot set property 'textContent' of null
at app.js:25
window.addEventListener('load', () => {
let long;
let lat;
let temperatureTimeZone = document.querySelector("temperature-timezone");
let temperatureDegree = document.querySelector("temperature-degree");
let temperatureDescription = document.querySelector("temperature-description");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
long = position.coords.longitude;
lat = position.coords.longitude;
const proxy = `https://cors-anywhere.herokuapp.com/`;
const api = `${proxy}https://api.darksky.net/forecast/1299787a9e937056e2ee6cb21ebfc2d4/${lat},${long}`;
fetch(api)
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
const { temperature, summary, precipType, icon } = data.currently;
// set Dom Elements from APi
temperatureDegree.textContent = temperature;
});
});
} else {
h1.textcontent = "Hey reload site and allow geolocation";
}
});
What is "temperature-degree"? If it's an id, then you must do "#temperature-degree". If it's a class, then you must do ".temperature-degree". If it's a tag, then you don't have any symbols, but "temperature-degree" shouldn't be a tag. If you're still confused, look at the documentation for it: developer.mozilla.org/docs/Web/API/Document/querySelector

Categories

Resources