Пятидневный прогноз погоды на карте openweathermap не дал ожидаемого результата - PullRequest
2 голосов
/ 03 августа 2020

Я пытаюсь получить прогноз погоды на 5 дней с помощью JS Fetch API, хотя я передаю cnt = 5, как указано в документации. Тем не менее, я получаю только текущую погоду. Я что-нибудь упустил?

fetch('https://api.openweathermap.org/data/2.5/weather?q=' + city+ '&appid=' + key+'&cnt=5') 

Я провел достаточно исследований и не смог определить, где именно я делаю ошибку. Любая помощь приветствуется.

const key = '**** Your API Key Here ****';

function weatherForecast(city) {
    fetch('https://api.openweathermap.org/data/2.5/weather?q=' + city+ '&appid=' + key+'&cnt=5')  
    .then(function(resp) {
        return resp.json() 
    })
    .then(function(data) {
        console.log('--->'+(JSON.stringify(data)));
        drawWeather(data);
    })
    .catch(function() {
        // catch any errors
    });
}

function drawWeather( d ) {
    var celcius = Math.round(parseFloat(d.main.temp)-273.15);
    var fahrenheit = Math.round(((parseFloat(d.main.temp)-273.15)*1.8)+32);
    var description = d.weather[0].description; 
    
    document.getElementById('description').innerHTML = description;
    document.getElementById('temp').innerHTML = fahrenheit + '°';
    document.getElementById('location').innerHTML = d.name+' '+d.sys.country;
}



//Event Listeners on button click
document.addEventListener("DOMContentLoaded", () => {
    // Handling button click
    document.querySelector(".button-search").addEventListener("click", () => {
        const searchedCity = document.querySelector('.text-search');
        console.log(searchedCity.value);
        if(searchedCity.value){
            weatherForecast(searchedCity.value);
        }       
   }) 
 });
body {
    font-family: 'Montserrat', sans-serif;
    font-weight: 400;
    font-size: 1.3em;
    height: 100vh;
}
h1 {
    margin: 0 auto;
    font-size: 2.2em;
    text-align: center;
    font-size: 10em;
}

.main-container,.search-component{
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 2em;
}

.text-search{
    width: 100%;
    max-width: 280px;
    padding: 10px 15px;
    border: solid blueviolet;
    color: #313131;
    font-size: 20px;
    font-weight: 300;
    transition: 0.2s ease-out;
}

.button-search{
   font-size: 32px;
}
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Current Weather</title>
  <link href="https://fonts.googleapis.com/css?family=Montserrat:400,900" rel="stylesheet">
  <link href="style.css" rel="stylesheet"> 
</head>
<body>
    <div class="search-component">
        <input type="text" autocomplete="off" class="text-search" placeholder="Type the City Name..." >
        <input type="button" class="button-search" value="Search">
    </div>

    <div class="main-container">
        <div>
            <div id="description"></div>
            <h1 id="temp"></h1>
            <div id="location"></div>
        </div>
    <div>
  <script src="main.js"></script>
</body>
</html>

Вот ответ JSON, который я получаю.

{
  "coord":{"lon":-74.01,"lat":40.71},
  "weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],
  "base":"stations",
  "main":{
    "temp":303.24,
    "feels_like":306.4,
    "temp_min":301.48,
    "temp_max":304.82,
    "pressure":1011,
    "humidity":74
  },
  "visibility":10000,
  "wind":{"speed":4.6,"deg":260},
  "clouds":{"all":1}, 
  "dt":1596415305,
  "sys":{
    "type":1,
    "id":4610,
    "country":"US",
    "sunrise":1596362046,
    "sunset":1596413419
  }
  "timezone":-14400,
  "id":5128581,
  "name":"New York",
  "cod":200
}

1 Ответ

2 голосов
/ 03 августа 2020

Для 5-дневного прогноза погоды вам нужно позвонить /forecast вместо /weather конечной точки.

Пример:

https://api.openweathermap.org/data/2.5/forecast?q=New%20York&appid=<your-api-key>&cnt=5
...