2024-05-05 20:55:51 +00:00
|
|
|
'use server'
|
2024-05-06 21:22:57 +00:00
|
|
|
import { Forecast, LocationType, coordType } from "@/types/types";
|
2024-05-05 20:55:51 +00:00
|
|
|
|
2024-05-06 21:22:57 +00:00
|
|
|
//takes address and returns coords in obj as {lat: number, lng: number}
|
|
|
|
export async function getLocation(searchLocation: string): Promise<coordType>{
|
2024-05-05 20:55:51 +00:00
|
|
|
const placesKey = "AIzaSyBf1ip4XogdC6XmbfDhxS_RJDOSieycJpQ";
|
2024-05-06 21:22:57 +00:00
|
|
|
const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${searchLocation}&key=${placesKey}`;
|
2024-05-05 20:55:51 +00:00
|
|
|
const res = await fetch(url);
|
|
|
|
if (!res.ok) {
|
|
|
|
throw new Error(`There was an error fetching the data`);
|
|
|
|
}
|
2024-05-06 21:22:57 +00:00
|
|
|
const data: LocationType = await res.json();
|
|
|
|
return data.results[0].geometry.location;
|
|
|
|
}
|
|
|
|
|
2024-05-08 06:53:30 +00:00
|
|
|
// takes coordinates in coordType format and returns json with weather forecast.
|
2024-05-06 21:22:57 +00:00
|
|
|
export async function getForecast(geoLocation: coordType): Promise<Forecast> {
|
|
|
|
const { lat, lng } = geoLocation;
|
2024-05-08 06:53:30 +00:00
|
|
|
const appId = '546911d860cb81f16585f7973b394b70';
|
2024-05-06 21:22:57 +00:00
|
|
|
const res = await fetch(
|
|
|
|
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${appId}`
|
|
|
|
);
|
|
|
|
if (!res.ok) {
|
|
|
|
throw new Error(`Failed to fetch the weather data`);
|
|
|
|
}
|
|
|
|
const data: Forecast = await res.json();
|
2024-05-05 20:55:51 +00:00
|
|
|
return data;
|
|
|
|
}
|