发布于 2026-01-06 3 阅读
0

使用 JavaScript 构建一个天气应用程序

使用 JavaScript 构建一个天气应用程序

我们开始吧!

要获取完整代码,请访问:GitHub

在开发天气应用程序之前,我们需要了解一些基本知识。

  • 我们需要使用API​​从天气预报平台获取天气数据。
  • 获取数据后,我们需要从中提取所需信息,例如:天气状况、温度等。

使用 AccuWeather API 获取天气数据

AccuWeather是一家提供国际天气预报服务的美国公司。

注意:要使用 Accuweather 的 API 获取天气信息,我们首先需要在 Accuweather 上创建一个用户帐户

替代文字

请访问Accuweather 教程

这是一个详细的视频教程,讲解如何开始使用 AccuWeather 以及如何获取 API,我们在代码中使用这些 API 来获取天气数据。

基本的HTML结构和CSS样式

我使用了Bootstrap进行基本样式设置。要获取 HTML 和 CSS 文件,请访问GitHub。

JavaScript 代码

创建一个新文件forecast.js

1.forecast.js文件

任务#1

首先,在 forecast.js 中,您需要初始化您的API 密钥。

const key = 'CXhPk82ZAZgV0ngVUWdVBVGePc4qMGqf';
Enter fullscreen mode Exit fullscreen mode

接下来,我们需要创建两个函数getCity()getWeather()使用这些函数,我们将从 AccuWeather 获取城市数据和该城市的天气状况。

const key = 'CXhPk82ZAZgV0ngVUWdVBVGePc4qMGqf';

const getCity = async(city) =>{/*code to fetch the city detail using API*/}

const getWeather = async(id) =>{/*code to fetch the weather detail using API*/}
Enter fullscreen mode Exit fullscreen mode

任务二

getCity()getWeather() 函数中,我们需要定义两个变量 url 和 query。

现在按如下方式初始化这些变量。

const getCity = async(city) =>{

    const url = 'https://dataservice.accuweather.com/locations/v1/cities/search';
    const query = `?apikey=${key}&q=${city}`
}

const getWeather = async(id) =>{

    const url = 'https://dataservice.accuweather.com/currentconditions/v1/'
    const query = `${id}?apikey=${key}`
}
Enter fullscreen mode Exit fullscreen mode

注意:要了解 API 密钥、URL 和查询,请观看上方提供的视频教程。

在上面的代码中,设置好 API 密钥、URL 和查询后,我们需要调用该fetch()方法并传递rrl“+”号query作为参数,从而生成完整的网址资源以访问数据。Fetch API 可以访问网络上的资源。您可以发起 HTTP 请求(使用 GET、POST 和其他方法)、下载和上传文件。该方法fetch()会启动一个请求并返回一个 Promise。请求完成后,Promise 会被解析并返回 Response 对象。

const key = 'CXhPk82ZAZgV0ngVUWdVBVGePc4qMGqf';

const getCity = async(city) =>{

    const url = 'https://dataservice.accuweather.com/locations/v1/cities/search';
    const query = `?apikey=${key}&q=${city}`

    const response = await fetch(url+query);
    const data = await response.json();
    return data[0];

}


const getWeather = async(id) =>{

    const url = 'https://dataservice.accuweather.com/currentconditions/v1/'
    const query = `${id}?apikey=${key}`
    const response = await fetch(url+query);
    const data = await response.json();

    return data[0];
}
Enter fullscreen mode Exit fullscreen mode

getCity()它们getWeather()是异步函数,因为它们都用 `async` 关键字标记了async。由于fetch()它们返回的是一个 Promise,所以你必须等待它被解析,这就是我们用 ` awaitasync` 关键字标记它的原因。
我们返回的是 `[0]` 类型0-index的数据return data[0],因为当 Promise 解析后,它会返回两种类型的数据:[0] 和 [1]。最准确的数据始终是第一个[0],所以这就是我们返回 `[ 0 [0]-index]` 类型数据的原因。

最后,我们将收到一个 JSON 格式的城市详细信息响应对象,getCity()情况也是如此,getWeather()因为它们返回的是 Promise,我们将在文件中处理这些 Promise app.js

2.app.js文件

在 app.js 中,我们有一个名为updateCity()如下所示的异步函数

let updateCity = async (city) =>{

    const cityName = await getCity(city);
    const weatherDetail = await getWeather(cityName.Key);

    return{cityName,weatherDetail};
}
Enter fullscreen mode Exit fullscreen mode

该函数返回一个包含城市详情和天气详情的对象。

因为异步函数总是返回一个 Promise,所以在下面的代码中,我们从用户那里获取城市名称,并将城市名称作为参数传递给updateCity()函数。我们知道updateCity()函数会返回一个 Promise,所以我们需要处理这个 Promise(如果 Promise 已解决,那么接下来该做什么?如果它未解决,则捕获错误)。

getCityForm.addEventListener('submit',e =>{
    e.preventDefault();

    const city = getCityForm.city.value.trim();
    getCityForm.reset();

    updateCity(city)
        .then(data => updateUI(data))
        .catch(err => {
            console.log(alert('Please enter a valid city name'))
            console.log(err);
        })
})
Enter fullscreen mode Exit fullscreen mode

当承诺达成后,我们需要更新用户界面,向用户显示详细信息。

所以,在上面的代码中,我们将已解析的 Promise 传递给updateUI()函数(该函数将更新我们的用户界面)。

const updateUI = (data) =>{

    wDetail.classList.remove('d-none')
    cityTime.classList.remove('d-none')
    const cityDetail = data.cityName;
    const weatherDetail = data.weatherDetail;
    degree.textContent = weatherDetail.Temperature.Metric.Value;
    condition.textContent = weatherDetail.WeatherText
    const weatherIconNumber = weatherDetail.WeatherIcon
    icon.setAttribute('src',`icons/${weatherIconNumber}.svg`)

    //from weather condition we will get timestamp 
    //So we have to convert it into real time
    const timestamp = weatherDetail.LocalObservationDateTime;
    const now = new Date(timestamp)
    curTime.textContent = now.toLocaleDateString()
    curCity.textContent = cityDetail.EnglishName
    if(weatherDetail.isDayTime){
        curMeridiem.textContent = "Day";
    }else{
        curMeridiem.textContent = 'Night';
    }
}
Enter fullscreen mode Exit fullscreen mode

updateUI()函数首先获取城市和天气详情的子详情(例如:温度、天气状况等),然后将这些详情渲染到屏幕上。

快!我们的天气应用已准备就绪

结论

感谢阅读本文!
如果您有任何疑问或想分享一些内容,请在下方留言!

文章来源:https://dev.to/fahadhassan1213/build-a-weather-app-using-javascript-2g3h