Skip to content

Commit

Permalink
[ADD] Fetch weather Data using Navigator Geolocation
Browse files Browse the repository at this point in the history
  • Loading branch information
naanaa59 committed Sep 11, 2024
1 parent 741efc4 commit 374cf8c
Show file tree
Hide file tree
Showing 10 changed files with 244 additions and 39 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
**/.vscode/
**/node_modules/
**/npm-debug.log*
server/api/.env
2 changes: 1 addition & 1 deletion client/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React</title>
<title>Clinema</title>
</head>
<body>
<div id="root"></div>
Expand Down
109 changes: 109 additions & 0 deletions client/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"eslint-plugin-react-refresh": "^0.4.9",
"globals": "^15.9.0",
"tailwindcss": "^3.4.10",
"axios": "^1.7.7",
"vite": "^5.4.1"
}
}
42 changes: 11 additions & 31 deletions client/src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,35 +1,15 @@
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
// src/App.jsx
// eslint-disable-next-line no-unused-vars
import React from 'react';
import LocationComponent from './LocationComponent'; // Import the LocationComponent

function App() {
const [count, setCount] = useState(0)

return (
<>
<div>
<a href="https://vitejs.dev" target="_blank">
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<p>
Edit <code>src/App.jsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
</>
)
return (
<div className="App">
<h1>Welcome to CliNema</h1>
<LocationComponent /> {/* Render the LocationComponent */}
</div>
);
}

export default App
export default App;
60 changes: 60 additions & 0 deletions client/src/LocationComponent.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { useEffect, useState } from 'react';
import axios from 'axios';

const LocationComponent = () => {
// eslint-disable-next-line no-unused-vars
const [latitude, setLatitude] = useState(null);
// eslint-disable-next-line no-unused-vars
const [longitude, setLongitude] = useState(null);
const [weatherData, setWeatherData] = useState(null);
const [error, setError] = useState(null);

useEffect(() => {
// Check if Geolocation API is available
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
setLatitude(latitude);
setLongitude(longitude);
console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);

// Send latitude and longitude to the Flask backend
axios.get(`http://localhost:5000/weather?lat=${latitude}&lon=${longitude}`)
.then(response => {
setWeatherData(response.data); // Set weather data in state
console.log("Weather data:", response.data); // Log the response data
})
.catch(err => {
console.error("Error fetching weather data:", err);
setError("Error fetching weather data");
});
},
(error) => {
console.error("Error getting location:", error);
setError("Error getting location");
}
);
} else {
console.log("Geolocation is not supported by this browser.");
setError("Geolocation is not supported by this browser.");
}
}, []); // The empty array ensures this runs once when the component mounts

return (
<div>
<h2>Your Location Weather</h2>
{weatherData ? (
<div>
<p>Temperature: {weatherData.main.temp}°C</p>
<p>Weather: {weatherData.weather[0]?.description}</p>
<p>Location: {weatherData.name}</p>
</div>
) : (
<p>{error ? error : "Fetching weather..."}</p>
)}
</div>
);
};

export default LocationComponent;
17 changes: 13 additions & 4 deletions client/vite.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
})
server: {
proxy: {
'/weather': {
target: 'http://localhost:5000', // Your Flask server URL
changeOrigin: true,
rewrite: (path) => path.replace(/^\/weather/, '/weather'),
},
},
},
});
2 changes: 2 additions & 0 deletions server/api/.env
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
MOVIE_API_HOST=0.0.0.0
MOVIE_API_PORT=5000
OPENWEATHER_API_KEY=9291dbdcabf7c26431129cb4438c30e1

47 changes: 45 additions & 2 deletions server/api/app.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,68 @@
#!/usr/bin/env python3
""" Starts the Flask web app """
import os

import requests
from dotenv import load_dotenv
from flask import Flask, jsonify
from flask import Flask, jsonify, request
from models import storage
from api.views import app_views
from flask_cors import CORS


load_dotenv()
app = Flask(__name__)
CORS(app)
app.url_map.strict_slashes = False
app.register_blueprint(app_views)
HOST = "0.0.0.0"
PORT = 5000
SECRET_KEY = os.getenv('SECRET_KEY')


OPENWEATHER_API_KEY = os.getenv('OPENWEATHER_API_KEY')


def get_weather(lat, lon):
base_url = "https://api.openweathermap.org/data/2.5/weather"
params = {
'lat': lat,
'lon': lon,
'appid': OPENWEATHER_API_KEY,
'units': 'metric'
}

response = requests.get(base_url, params=params)

if response.status_code == 200:
print(response.json)
return response.json() # Return the weather data as JSON
else:
return None # Return None if the request failed


@app.route('/weather', methods=['GET'])
def weather():
lat = request.args.get('lat')
lon = request.args.get('lon')

print(f'Latitude: {lat}, Longitude: {lon}')

if not lat or not lon:
return jsonify({'error': 'Missing latitude or longitude'}), 400

weather_data = get_weather(lat, lon)

if weather_data:
return jsonify(weather_data)
else:
return jsonify({'error': 'Failed to fetch weather data'}), 500


@app.route('/volumes')
def volume():
""" A dummy route to test volumes of docker"""
return "Testing volumes: -Zidane Square headed-"
return "Testing volumes: -Zidane -"


@app.teardown_appcontext
Expand Down
Loading

0 comments on commit 374cf8c

Please sign in to comment.