利用OpenWeatherMap API构建天气预报应用:

星空下的诗人 2019-07-10 ⋅ 19 阅读

引言

天气预报是我们日常生活中经常需要关注的信息之一。借助现代技术,我们可以轻松地构建一个天气预报应用,并通过OpenWeatherMap API获取准确、实时的天气数据。在本篇博客中,我们将分别使用React和Angular两种流行的前端框架来构建天气预报应用。

使用React构建天气预报应用

安装依赖

首先,我们需要使用create-react-app命令行工具来创建一个React项目。打开终端,运行以下命令:

npx create-react-app weather-app-react

进入项目目录并安装相关依赖:

cd weather-app-react
npm install axios
npm install react-icons

获取天气数据

我们将使用axios库来进行HTTP请求以获取天气数据。在根目录下创建一个名为api.js的文件,并添加以下内容:

import axios from 'axios';

const API_KEY = 'YOUR_API_KEY';
const API_URL = 'http://api.openweathermap.org/data/2.5/weather';

export const getWeatherData = async (city) => {
  try {
    const response = await axios.get(`${API_URL}?q=${city}&appid=${API_KEY}`);
    return response.data;
  } catch (error) {
    throw error;
  }
};

请注意替换API_KEY为您在OpenWeatherMap官网上获得的API密钥。

构建应用界面

src文件夹下创建一个名为Weather.js的文件,并添加以下内容:

import React, { useEffect, useState } from 'react';
import { WiDaySunny, WiCloud, WiRain, WiSnow } from 'react-icons/wi';
import { getWeatherData } from './api';

const Weather = () => {
  const [loading, setLoading] = useState(true);
  const [weatherData, setWeatherData] = useState({});
  const [city, setCity] = useState('');

  useEffect(() => {
    const fetchData = async () => {
      try {
        const data = await getWeatherData('Beijing');
        setWeatherData(data);
        setLoading(false);
      } catch (error) {
        console.error(error);
      }
    };

    fetchData();
  }, []);

  const handleCityChange = (event) => {
    setCity(event.target.value);
  };

  const handleSearch = async () => {
    setLoading(true);
    try {
      const data = await getWeatherData(city);
      setWeatherData(data);
      setLoading(false);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <div>
      <input placeholder="Enter city" value={city} onChange={handleCityChange} />
      <button onClick={handleSearch}>Search</button>
      
      {loading ? (
        <div>Loading...</div>
      ) : (
        <div>
          <h1>{weatherData.name}</h1>
          <h2>{weatherData.weather[0].description}</h2>
          <div>
            {weatherData.weather[0].main === 'Clear' && <WiDaySunny />}
            {weatherData.weather[0].main === 'Clouds' && <WiCloud />}
            {weatherData.weather[0].main === 'Rain' && <WiRain />}
            {weatherData.weather[0].main === 'Snow' && <WiSnow />}
          </div>
        </div>
      )}
    </div>
  );
};

export default Weather;

这个组件将显示一个输入框和一个搜索按钮,用户可以输入城市名称并获取该城市的天气数据。

加载Weather组件

找到src文件夹下的App.js文件,并修改为以下内容:

import React from 'react';
import Weather from './Weather';

const App = () => {
  return (
    <div className="App">
      <Weather />
    </div>
  );
};

export default App;

运行应用

在终端中运行以下命令来启动React应用:

npm start

现在,您可以在浏览器中访问http://localhost:3000来查看并使用天气预报应用。

使用Angular构建天气预报应用

安装依赖

首先,我们需要使用Angular CLI来创建一个新的Angular项目。打开终端,运行以下命令:

ng new weather-app-angular

进入项目目录并安装相关依赖:

cd weather-app-angular
npm install axios
npm install react-icons

获取天气数据

我们将使用axios库来进行HTTP请求以获取天气数据。在项目根目录的src文件夹下创建一个名为api.ts的文件,并添加以下内容:

import axios from 'axios';

const API_KEY = 'YOUR_API_KEY';
const API_URL = 'http://api.openweathermap.org/data/2.5/weather';

export const getWeatherData = async (city: string) => {
  try {
    const response = await axios.get(`${API_URL}?q=${city}&appid=${API_KEY}`);
    return response.data;
  } catch (error) {
    throw error;
  }
};

请注意替换API_KEY为您在OpenWeatherMap官网上获得的API密钥。

构建应用界面

src/app文件夹下创建一个名为weather的文件夹,并在其中创建一个名为weather.component.html的HTML模板文件,内容如下:

<input placeholder="Enter city" [(ngModel)]="city" />
<button (click)="handleSearch()">Search</button>

<div *ngIf="loading">Loading...</div>
<div *ngIf="!loading">
  <h1>{{ weatherData.name }}</h1>
  <h2>{{ weatherData.weather[0].description }}</h2>
  <div>
    <i *ngIf="weatherData.weather[0].main === 'Clear'" class="wi wi-day-sunny"></i>
    <i *ngIf="weatherData.weather[0].main === 'Clouds'" class="wi wi-cloud"></i>
    <i *ngIf="weatherData.weather[0].main === 'Rain'" class="wi wi-rain"></i>
    <i *ngIf="weatherData.weather[0].main === 'Snow'" class="wi wi-snow"></i>
  </div>
</div>

src/app/weather文件夹下创建一个名为weather.component.ts的TypeScript文件,并添加以下内容:

import { Component, OnInit } from '@angular/core';
import { getWeatherData } from '../../api';

@Component({
  selector: 'app-weather',
  templateUrl: './weather.component.html',
  styleUrls: ['./weather.component.css']
})
export class WeatherComponent implements OnInit {
  loading: boolean = true;
  weatherData: any = {};
  city: string = '';

  ngOnInit(): void {
    this.fetchData('Beijing');
  }

  handleSearch(): void {
    this.fetchData(this.city);
  }

  async fetchData(city: string): Promise<void> {
    this.loading = true;
    try {
      const data = await getWeatherData(city);
      this.weatherData = data;
      this.loading = false;
    } catch (error) {
      console.error(error);
    }
  }
}

加载Weather组件

找到src/app/app.component.html文件,并修改为以下内容:

<div class="container">
  <app-weather></app-weather>
</div>

运行应用

在终端中运行以下命令来启动Angular应用:

ng serve --open

现在,您可以在浏览器中访问http://localhost:4200来查看并使用天气预报应用。

总结

在本篇博客中,我们学习了如何使用React和Angular分别构建一个天气预报应用。我们利用了OpenWeatherMap API来获取天气数据,并展示了城市名称、天气描述和相应的天气图标。通过学习本篇博客,您可以进一步探索和扩展这两个应用,并在实际项目中应用相关技术。

参考资料:


全部评论: 0

    我有话说: