问题描述
我正在尝试基于 openweathermap API 构建一个简单的 MagicMirror 浏览器内天气应用。
对编码知之甚少,这证明有点困难。我有这个代码,有人为我纠正过,但它不会在旧设备上运行。 Here's the sandbox link。
class Weather {
constructor(data) {
this.data = data;
this.temp = Math.round(data.main.temp);
this.feels_like = Math.round(data.main.feels_like);
this.description = data.weather[0].description;
this.city = data.name;
this.country = data.sys.country;
this.wind = Math.round(data.wind.speed);
this.humidity = data.main.humidity;
}
geticonClass() {
let prefix = this.data.weather[0].icon.endsWith("d")
? 'wi-owm-day-'
: 'wi-owm-night-';
return `${prefix}${this.data.weather[0].id}`;
}
}
function fetchWeather() {
navigator.geolocation.getCurrentPosition(
async (position) => {
let url = new URL("https://api.openweathermap.org/data/2.5/weather");
url.searchParams.set("lat",position.coords.latitude);
url.searchParams.set("lon",position.coords.longitude);
url.searchParams.set("lang","pl");
url.searchParams.set("appid","fb7164d50e0faf1f058561b7903f03b9");
url.searchParams.set("units","metric");
const response = await fetch(url);
const weatherjson = await response.json();
updateDOM(new Weather(weatherjson));
},(error) => {
console.error("Unable to get geolocation,Unsuported maybe?");
}
);
}
function updateDOM(weather) {
const iconElement = document.querySelector(".today-weather-icon i");
const tempElement = document.querySelector(".temperature-value p");
const tempFeelElement = document.querySelector(".temperature-feel p");
const descElement = document.querySelector(".temperature-description p");
const locationElement = document.querySelector(".location p");
const windElement = document.querySelector(".wind p");
const humidElement = document.querySelector(".humid p");
iconElement.classList.add(weather.geticonClass());
tempElement.innerHTML = `${weather.temp}°<span>C</span>`;
tempFeelElement.innerHTML = `Odczuwalna: ${weather.feels_like}°<span>C</span>`;
descElement.innerHTML = weather.description;
locationElement.innerHTML = `${weather.city},${weather.country}`;
windElement.innerHTML = ` ${weather.wind} km/h`;
humidElement.innerHTML = ` ${weather.humidity}`;
}
fetchWeather();
setInterval(fetchWeather,1800000);
updateDOM();
setInterval(updateDOM,1820000);
Here's a previous version of the code with navigator.geolocation that worked.
解决方法
您正在使用现代 ES6 语法,例如 class Weather
这就是原因。如果您想了解更多关于如何将其转换为 ES6 之前的语法以便它也适用于旧设备的信息,请查看这篇文章 ES6 Class vs Object.prototyoe
`