Skip to content

Commit a00e212

Browse files
committed
get weather by coords or ip
1 parent b495f45 commit a00e212

File tree

3 files changed

+49
-29
lines changed

3 files changed

+49
-29
lines changed

backend/src/routes/weather.route.ts

Lines changed: 37 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -13,35 +13,48 @@ export const weatherRoute = Router();
1313
*/
1414
weatherRoute.get('/', async (req: Request, res: Response): Promise<void> => {
1515
try {
16-
const { latitude, longitude } = req.query;
17-
18-
if (!latitude || !longitude) {
19-
res.status(StatusCodes.BAD_REQUEST).json({
20-
message: 'Please provide both latitude and longitude as query parameters.'
21-
});
16+
let latitude, longitude;
17+
// Extract client IP (supports proxies)
18+
if (!req.query.latitude && !req.query.longitude) {
19+
const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
20+
21+
console.log(`Fetching location for IP: ${ip}`);
22+
23+
// Fetch geolocation data using ip-api.com
24+
const geoResponse = await axios.get(`http://ip-api.com/json/${ip}`);
25+
const { lat, lon, city, country, status } = geoResponse.data;
26+
latitude = lat;
27+
longitude = lon;
28+
29+
if (status !== 'success') {
30+
res.status(400).json({ error: 'Unable to determine location from IP' });
31+
console.error(`Error fetching weather: ${ip}`);
32+
return;
33+
}
34+
console.log(`Determined location: ${city}, ${country} (${lat}, ${lon})`);
35+
} else {
36+
latitude = req.query.latitude;
37+
longitude = req.query.longitude;
2238
}
2339

24-
// Construct the Open-Meteo API URL:
25-
const apiUrl = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current=temperature_2m,weathercode,windspeed_10m&daily=temperature_2m_max,temperature_2m_min,weathercode,sunrise,sunset&timezone=auto`;
26-
27-
// Fetch data from the Open-Meteo API using Axios
28-
const { data, status } = await axios.get(apiUrl);
2940

30-
// If status is not 200, treat it as an error
31-
if (status !== StatusCodes.OK) {
32-
res.status(StatusCodes.BAD_REQUEST).json({
33-
message: 'Failed to fetch data from Open-Meteo'
34-
});
35-
}
41+
// Fetch weather data from Open-Meteo
42+
const weatherResponse = await axios.get('https://api.open-meteo.com/v1/forecast', {
43+
params: {
44+
latitude: latitude,
45+
longitude: longitude,
46+
current: 'temperature_2m,weathercode,windspeed_10m',
47+
daily: 'temperature_2m_max,temperature_2m_min,weathercode,sunrise,sunset',
48+
timezone: 'auto'
49+
}
50+
});
51+
console.log(weatherResponse.data);
3652

37-
// Return the JSON data from Open-Meteo
38-
res.status(StatusCodes.OK).json(data);
53+
res.json(
54+
weatherResponse.data
55+
);
3956

4057
} catch (error) {
41-
// Handle unexpected errors (e.g., network issues)
42-
res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({
43-
message: 'Error fetching weather data',
44-
error: (error as Error).message,
45-
});
58+
console.error('Error fetching weather:', error);
4659
}
4760
});

frontend/src/api/dash-api.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ export class DashApi {
4040
return null;
4141
}
4242

43-
public static async getWeather(latitude: number, longitude: number): Promise<any> {
43+
public static async getWeather(latitude?: number, longitude?: number): Promise<any> {
4444
const res = await axios.get(`${BACKEND_URL}/api/weather`, {
4545
params: {
4646
latitude,

frontend/src/components/widgets/WeatherWidget.tsx

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -85,14 +85,21 @@ export const WeatherWidget: React.FC = () => {
8585

8686
useEffect(() => {
8787
const fetchWeather = async () => {
88-
if (!location) return;
8988
setLoading(true);
9089
try {
91-
const data = await DashApi.getWeather(location.latitude, location.longitude);
92-
console.log('Weather data:', data);
90+
let data;
91+
if (!location) {
92+
console.log('no location');
93+
94+
data = await DashApi.getWeather();
95+
console.log('Weather data:', data);
96+
} else {
97+
data = await DashApi.getWeather(location.latitude, location.longitude);
98+
console.log('Weather data:', data);
99+
}
93100
setWeatherData(data);
94101
} catch (error) {
95-
console.error('Error fetching weather:', error);
102+
console.log('Error fetching weather:', error);
96103
} finally {
97104
setLoading(false);
98105
}

0 commit comments

Comments
 (0)