26 - Weather Forecast App with Location Detection

Description:

Create a React application that provides a weather forecast app with location detection. The app should automatically detect the user's location, allow users to manually enter a location if desired, fetch weather data from a weather API based on the chosen location, and display the current weather conditions, including temperature, humidity, wind speed, and weather description.

Algorithm

  1. Create a state variable to store the user's location and weather data.

  2. Define a function to automatically detect the user's location using the Geolocation API.

  3. Define a function to handle manual location input.

  4. Define a function to fetch weather data from a weather API based on the chosen location.

  5. Define a function to display the current weather conditions.

  6. Render the weather forecast app interface.

Classes

  • WeatherForecastApp: A component that represents the weather forecast app interface.

  • LocationDetector: A component that represents the location detection functionality.

  • WeatherDataFetcher: A component that represents the weather data fetching functionality.

  • WeatherConditionsDisplay: A component that represents the weather conditions display.

Code

WeatherForecastApp.js

import React, { useState, useEffect } from 'react';
import LocationDetector from './LocationDetector';
import WeatherDataFetcher from './WeatherDataFetcher';
import WeatherConditionsDisplay from './WeatherConditionsDisplay';

function WeatherForecastApp() {
  const [location, setLocation] = useState('');
  const [weatherData, setWeatherData] = useState({});

  useEffect(() => {
    const detectLocation = async () => {
      const userLocation = await LocationDetector.detectLocation();
      setLocation(userLocation);
    };
    detectLocation();
  }, []);

  const handleManualLocationInput = (location) => {
    setLocation(location);
  };

  const fetchWeatherData = async () => {
    const weatherData = await WeatherDataFetcher.fetchWeatherData(location);
    setWeatherData(weatherData);
  };

  useEffect(() => {
    fetchWeatherData();
  }, [location]);

  return (
    <div>
      <h2>Weather Forecast App</h2>
      <LocationDetector onLocationDetect={handleManualLocationInput} />
      <WeatherDataFetcher />
      <WeatherConditionsDisplay weatherData={weatherData} />
    </div>
  );
}

export default WeatherForecastApp;

LocationDetector.js

import React from 'react';

function LocationDetector({ onLocationDetect }) {
  const handleDetectLocation = async () => {
    const userLocation = await navigator.geolocation.getCurrentPosition(
      (position) => {
        const latitude = position.coords.latitude;
        const longitude = position.coords.longitude;
        const location = `${latitude}, ${longitude}`;
        onLocationDetect(location);
      }
    );
  };

  return (
    <button onClick={handleDetectLocation}>
      Detect Location
    </button>
  );
}

export default LocationDetector;

WeatherDataFetcher.js

import React from 'react';
import axios from 'axios';

function WeatherDataFetcher() {
  const fetchWeatherData = async (location) => {
    const apiURL = `<weather-url`>;
    const response = await axios.get(apiURL);
    const weatherData = response.data;
    return weatherData;
  };

  return <div />;
}

export default WeatherDataFetcher;

WeatherConditionsDisplay.js

import React from 'react';

function WeatherConditionsDisplay({ weatherData }) {
  const temperature = weatherData.temp_c;
  const humidity = weatherData.humidity;
  const windSpeed = weatherData.wind_mph;
  const weatherDescription = weatherData.condition.text;

  return (
    <div>
      <h3>Current Weather Conditions</h3>
      <p>Temperature: {temperature}°C</p>
      <p>Humidity: {humidity}%</p>
      <p>Wind Speed: {windSpeed} mph</p>
      <p>Weather Description: {weatherDescription}</p>
    </div>
  );
}

export default WeatherConditionsDisplay;

Explanation

The WeatherForecastApp component renders the weather forecast app interface. The LocationDetector component detects the user's location using the Geolocation API. The WeatherDataFetcher component fetches weather data from a weather API based on the chosen location. The WeatherConditionsDisplay component displays the current weather conditions.

Possible Future Enhancements

  • Add more weather data to the display, such as precipitation and UV index.

  • Improve the user interface and user experience.

  • Add support for multiple weather APIs.

  • Allow users to save their favorite locations for quick access.

  • Display weather forecasts for multiple days.

Last updated