json 如何使用API在Javascript天气应用程序中将城市搜索限制在某些国家

gc0ot86w  于 2023-03-04  发布在  Java
关注(0)|答案(1)|浏览(133)

我使用OpenWeatherMap API为我的一门课上的作业构建了一个非常简单的天气应用程序,但我发现我的解决方案非常笨拙,它不符合我的教授设定的所有标准。我的教授告诉我们使用5天/ 3小时的预报来显示最低/最高温度、湿度、天气状况、和一个适当的图标,为未来5天,但问题是,事实上,上述预报显示其信息在3小时的间隔,这意味着最低/最高温度为每一天并不真正可用。(如果我没有弄错)
此外,我需要限制搜索的城市为美国城市,但我不知道如何在JS中做到这一点,也找不到一种方法来指定它在API调用。
现在,由于5天/3小时调用输出数据的方式,我不得不为每一天创建一个元素,并为其给予相应的数据,如下所示:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Weather app</title>
  </head>
  <body>
    <h1>Weather forecast</h1>
    <form id="cityForm">
      <label for="city">Enter City Name:</label>
      <input type="text" id="city" name="city" />
      <br /><br />
      <input type="submit" value="Submit" />
    </form>
    <div id="output"></div>
    <script>
      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);
      }
    </script>
  </body>
</html>

下面是我从5天/ 3小时API调用中获得的数据的屏幕截图。您可以在数组的第二项中的main下找到temp_min/ temp_max。

u3r8eeie

u3r8eeie1#

api.openweathermap.org/data/2.5/forecast?q={city name},{country code}&appid={API key}

我建议在请求中使用国家代码。

相关问题