【发布时间】:2021-05-16 20:34:55
【问题描述】:
我正在尝试基于 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/ECMAScript 2015 中添加了 JavaScript 中的类,如果您的设备浏览器不支持 ES6,它将无法识别。您能否提供有关“旧设备”定义的更多信息?还有那些旧设备使用的是什么类型的浏览器?
-
@Pascal 我现在已经尝试了多种设备:Android 8 上的 Firefox 85.1.3 和 Chrome 88.0.4324.152,Android 4.0.4 上的 Firefox 51.04.4,Android 4.2 上的 Firefox 51.04.4。 Android 5.1.1 上的 2 和 Firefox 85.1.3。它仅适用于 Firefox 85.1.3 Android 10 和带有 Win10 的桌面。
标签: javascript android backwards-compatibility openweathermap