Я построил приложение для погоды с голыми костями для задания в классе, который я принимаю, используя API OpenWeatherMap, но я считаю, что мое решение очень неловко и не соответствует всем критериям, установленным моим профессором. Указанный прогноз отображает свою информацию с 3-часовыми интервалами, что означает, что температура MIN/MAX для каждого дня действительно не доступна для использования. (Если я не ошибаюсь)
Кроме того, мне нужно ограничить города, доступные для поиска в США, но я не знаю, как сделать это в JS и не могу найти способ указать их в вызове API. это: < /p>
Weather app
Weather forecast
Enter City Name:
function getWeather(query) {
var url =
"http://api.openweathermap.org/data/2.5/forecast?q=" +
query +
"&units=imperial&APPID=56866f8407bb1e2d63330f3c046f35af";
fetch(url)
.then((response) => response.json())
.then((data) => displayWeather(data)); //call displayWeather function
}
document
.getElementById("cityForm")
.addEventListener("submit", function (event) {
event.preventDefault(); // prevent the form from submitting
var city = document.getElementById("city").value; // get the city name from the input field
getWeather(city);
});
function displayWeather(weather) {
console.log(weather);
var resultContainer = document.querySelector("#output");
var cityName = document.createElement("h2");
resultContainer.append(cityName);
var forecastDate1 = document.createElement("p"); // Creating elements
var forecastDate2 = document.createElement("p");
var forecastDate3 = document.createElement("p");
var forecastDate4 = document.createElement("p");
var forecastDate5 = document.createElement("p");
cityName.textContent = weather.city.name;
var icon = document.createElement("img");
var iconUrl =
"http://openweathermap.org/img/w/" +
weather.list[0].weather[0].icon +
".png";
icon.setAttribute("src", iconUrl);
var description = document.createElement("p");
var day1 = new Date(weather.list[0].dt * 1000);
const month1 = day1.getMonth() + 1;
const firstDay = day1.getDate();
const year1 = day1.getFullYear();
const outputDateStr1 = `${month1.toString().padStart(2, "0")}/${firstDay
.toString()
.padStart(2, "0")}/${year1.toString()}`;
var day2 = new Date(weather.list[8].dt * 1000);
const month2 = day2.getMonth() + 1;
const secondDay = day2.getDate();
const year2 = day2.getFullYear();
const outputDateStr2 = `${month2
.toString()
.padStart(2, "0")}/${secondDay
.toString()
.padStart(2, "0")}/${year2.toString()}`;
var day3 = new Date(weather.list[16].dt * 1000);
const month3 = day3.getMonth() + 1;
const thirdDay = day3.getDate();
const year3 = day3.getFullYear();
const outputDateStr3 = `${month3.toString().padStart(2, "0")}/${thirdDay
.toString()
.padStart(2, "0")}/${year3.toString()}`;
var day4 = new Date(weather.list[24].dt * 1000);
const month4 = day4.getMonth() + 1;
const fourthDay = day4.getDate();
const year4 = day4.getFullYear();
const outputDateStr4 = `${month4
.toString()
.padStart(2, "0")}/${fourthDay
.toString()
.padStart(2, "0")}/${year4.toString()}`;
var day5 = new Date(weather.list[32].dt * 1000);
const month5 = day5.getMonth() + 1;
const fifthDay = day5.getDate();
const year5 = day5.getFullYear();
const outputDateStr5 = `${month5.toString().padStart(2, "0")}/${fifthDay
.toString()
.padStart(2, "0")}/${year5.toString()}`;
forecastDate1.textContent = `${outputDateStr1}
Min ${weather.list[0].main.temp_min} F
Max: ${weather.list[0].main.temp_max} F
Humidity: ${weather.list[0].main.humidity}%
Weather conditions: ${weather.list[0].weather[0].description}`;
var icon1 = document.createElement("img");
var iconUrl1 =
"http://openweathermap.org/img/w/" +
weather.list[0].weather[0].icon +
".png";
icon1.setAttribute("src", iconUrl1);
forecastDate1.append(icon1);
forecastDate2.textContent = `${outputDateStr2}
Min ${weather.list[8].main.temp_min} F
Max: ${weather.list[8].main.temp_max} F
Humidity: ${weather.list[8].main.humidity}%
Weather conditions: ${weather.list[8].weather[0].description}`;
var icon2 = document.createElement("img");
var iconUrl2 =
"http://openweathermap.org/img/w/" +
weather.list[8].weather[0].icon +
".png";
icon2.setAttribute("src", iconUrl2);
forecastDate2.append(icon2);
forecastDate3.textContent = `${outputDateStr3}
Min ${weather.list[16].main.temp_min} F
Max: ${weather.list[16].main.temp_max} F
Humidity: ${weather.list[16].main.humidity}%
Weather conditions: ${weather.list[16].weather[0].description}`;
var icon3 = document.createElement("img");
var iconUrl3 =
"http://openweathermap.org/img/w/" +
weather.list[16].weather[0].icon +
".png";
icon3.setAttribute("src", iconUrl3);
forecastDate3.append(icon3);
forecastDate4.textContent = `${outputDateStr4}
Min ${weather.list[24].main.temp_min} F
Max: ${weather.list[24].main.temp_max} F
Humidity: ${weather.list[24].main.humidity}%
Weather conditions: ${weather.list[24].weather[0].description}`;
var icon4 = document.createElement("img");
var iconUrl4 =
"http://openweathermap.org/img/w/" +
weather.list[24].weather[0].icon +
".png";
icon4.setAttribute("src", iconUrl4);
forecastDate4.append(icon4);
forecastDate5.textContent = `${outputDateStr5}
Min ${weather.list[32].main.temp_min} F
Max: ${weather.list[32].main.temp_max} F
Humidity: ${weather.list[32].main.humidity}%
Weather conditions: ${weather.list[32].weather[0].description}`;
var icon5 = document.createElement("img");
var iconUrl5 =
"http://openweathermap.org/img/w/" +
weather.list[32].weather[0].icon +
".png";
icon5.setAttribute("src", iconUrl5);
forecastDate5.append(icon5);
resultContainer.append(forecastDate1);
resultContainer.append(forecastDate2);
resultContainer.append(forecastDate3);
resultContainer.append(forecastDate4);
resultContainer.append(forecastDate5);
}
< /code>
Вот скриншот данных, которые я получаю из 5-дневного /3-часового вызова API. Вы можете найти temp_min/temp_max в Main во втором элементе массива.>
Подробнее здесь: https://stackoverflow.com/questions/756 ... r-app-usin
Как ограничить поиск городов в определенную страну в приложении JavaScript Weath ⇐ Html
Программисты Html
1759140882
Anonymous
Я построил приложение для погоды с голыми костями для задания в классе, который я принимаю, используя API OpenWeatherMap, но я считаю, что мое решение очень неловко и не соответствует всем критериям, установленным моим профессором. Указанный прогноз отображает свою информацию с 3-часовыми интервалами, что означает, что температура MIN/MAX для каждого дня действительно не доступна для использования. (Если я не ошибаюсь)
Кроме того, мне нужно ограничить города, доступные для поиска в США, но я не знаю, как сделать это в JS и не могу найти способ указать их в вызове API. это: < /p>
Weather app
Weather forecast
Enter City Name:
function getWeather(query) {
var url =
"http://api.openweathermap.org/data/2.5/forecast?q=" +
query +
"&units=imperial&APPID=56866f8407bb1e2d63330f3c046f35af";
fetch(url)
.then((response) => response.json())
.then((data) => displayWeather(data)); //call displayWeather function
}
document
.getElementById("cityForm")
.addEventListener("submit", function (event) {
event.preventDefault(); // prevent the form from submitting
var city = document.getElementById("city").value; // get the city name from the input field
getWeather(city);
});
function displayWeather(weather) {
console.log(weather);
var resultContainer = document.querySelector("#output");
var cityName = document.createElement("h2");
resultContainer.append(cityName);
var forecastDate1 = document.createElement("p"); // Creating elements
var forecastDate2 = document.createElement("p");
var forecastDate3 = document.createElement("p");
var forecastDate4 = document.createElement("p");
var forecastDate5 = document.createElement("p");
cityName.textContent = weather.city.name;
var icon = document.createElement("img");
var iconUrl =
"http://openweathermap.org/img/w/" +
weather.list[0].weather[0].icon +
".png";
icon.setAttribute("src", iconUrl);
var description = document.createElement("p");
var day1 = new Date(weather.list[0].dt * 1000);
const month1 = day1.getMonth() + 1;
const firstDay = day1.getDate();
const year1 = day1.getFullYear();
const outputDateStr1 = `${month1.toString().padStart(2, "0")}/${firstDay
.toString()
.padStart(2, "0")}/${year1.toString()}`;
var day2 = new Date(weather.list[8].dt * 1000);
const month2 = day2.getMonth() + 1;
const secondDay = day2.getDate();
const year2 = day2.getFullYear();
const outputDateStr2 = `${month2
.toString()
.padStart(2, "0")}/${secondDay
.toString()
.padStart(2, "0")}/${year2.toString()}`;
var day3 = new Date(weather.list[16].dt * 1000);
const month3 = day3.getMonth() + 1;
const thirdDay = day3.getDate();
const year3 = day3.getFullYear();
const outputDateStr3 = `${month3.toString().padStart(2, "0")}/${thirdDay
.toString()
.padStart(2, "0")}/${year3.toString()}`;
var day4 = new Date(weather.list[24].dt * 1000);
const month4 = day4.getMonth() + 1;
const fourthDay = day4.getDate();
const year4 = day4.getFullYear();
const outputDateStr4 = `${month4
.toString()
.padStart(2, "0")}/${fourthDay
.toString()
.padStart(2, "0")}/${year4.toString()}`;
var day5 = new Date(weather.list[32].dt * 1000);
const month5 = day5.getMonth() + 1;
const fifthDay = day5.getDate();
const year5 = day5.getFullYear();
const outputDateStr5 = `${month5.toString().padStart(2, "0")}/${fifthDay
.toString()
.padStart(2, "0")}/${year5.toString()}`;
forecastDate1.textContent = `${outputDateStr1}
Min ${weather.list[0].main.temp_min} F
Max: ${weather.list[0].main.temp_max} F
Humidity: ${weather.list[0].main.humidity}%
Weather conditions: ${weather.list[0].weather[0].description}`;
var icon1 = document.createElement("img");
var iconUrl1 =
"http://openweathermap.org/img/w/" +
weather.list[0].weather[0].icon +
".png";
icon1.setAttribute("src", iconUrl1);
forecastDate1.append(icon1);
forecastDate2.textContent = `${outputDateStr2}
Min ${weather.list[8].main.temp_min} F
Max: ${weather.list[8].main.temp_max} F
Humidity: ${weather.list[8].main.humidity}%
Weather conditions: ${weather.list[8].weather[0].description}`;
var icon2 = document.createElement("img");
var iconUrl2 =
"http://openweathermap.org/img/w/" +
weather.list[8].weather[0].icon +
".png";
icon2.setAttribute("src", iconUrl2);
forecastDate2.append(icon2);
forecastDate3.textContent = `${outputDateStr3}
Min ${weather.list[16].main.temp_min} F
Max: ${weather.list[16].main.temp_max} F
Humidity: ${weather.list[16].main.humidity}%
Weather conditions: ${weather.list[16].weather[0].description}`;
var icon3 = document.createElement("img");
var iconUrl3 =
"http://openweathermap.org/img/w/" +
weather.list[16].weather[0].icon +
".png";
icon3.setAttribute("src", iconUrl3);
forecastDate3.append(icon3);
forecastDate4.textContent = `${outputDateStr4}
Min ${weather.list[24].main.temp_min} F
Max: ${weather.list[24].main.temp_max} F
Humidity: ${weather.list[24].main.humidity}%
Weather conditions: ${weather.list[24].weather[0].description}`;
var icon4 = document.createElement("img");
var iconUrl4 =
"http://openweathermap.org/img/w/" +
weather.list[24].weather[0].icon +
".png";
icon4.setAttribute("src", iconUrl4);
forecastDate4.append(icon4);
forecastDate5.textContent = `${outputDateStr5}
Min ${weather.list[32].main.temp_min} F
Max: ${weather.list[32].main.temp_max} F
Humidity: ${weather.list[32].main.humidity}%
Weather conditions: ${weather.list[32].weather[0].description}`;
var icon5 = document.createElement("img");
var iconUrl5 =
"http://openweathermap.org/img/w/" +
weather.list[32].weather[0].icon +
".png";
icon5.setAttribute("src", iconUrl5);
forecastDate5.append(icon5);
resultContainer.append(forecastDate1);
resultContainer.append(forecastDate2);
resultContainer.append(forecastDate3);
resultContainer.append(forecastDate4);
resultContainer.append(forecastDate5);
}
< /code>
Вот скриншот данных, которые я получаю из 5-дневного /3-часового вызова API. Вы можете найти temp_min/temp_max в Main во втором элементе массива.>
Подробнее здесь: [url]https://stackoverflow.com/questions/75609185/how-to-limit-search-for-cities-to-certain-country-in-javascript-weather-app-usin[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия