2024-05-17 23:57:46 +00:00
|
|
|
import { NextRequest, NextResponse } from "next/server";
|
|
|
|
import { coordType, LocationType } from "@/types/types";
|
2024-05-17 23:02:29 +00:00
|
|
|
|
2024-05-17 23:57:46 +00:00
|
|
|
export async function GET(request: NextRequest) {
|
|
|
|
const searchParams = new URL(request.url).searchParams;
|
|
|
|
const searchLocation = searchParams.get("location");
|
|
|
|
|
|
|
|
if (!searchLocation) {
|
|
|
|
return NextResponse.json(
|
|
|
|
{ error: "Location parameter is required" },
|
|
|
|
{ status: 400 }
|
|
|
|
);
|
|
|
|
}
|
2024-05-05 20:55:51 +00:00
|
|
|
|
2024-05-17 23:02:29 +00:00
|
|
|
const placesKey = process.env.PLACES_API;
|
|
|
|
if (!placesKey) {
|
|
|
|
console.error("PLACES_API environment variable is not set");
|
2024-05-17 23:57:46 +00:00
|
|
|
return NextResponse.json(
|
|
|
|
{ error: "PLACES_API environment variable is not set" },
|
|
|
|
{ status: 500 }
|
|
|
|
);
|
2024-05-06 21:22:57 +00:00
|
|
|
}
|
2024-05-17 23:02:29 +00:00
|
|
|
|
|
|
|
const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${searchLocation}&key=${placesKey}`;
|
2024-05-17 23:57:46 +00:00
|
|
|
console.log("Fetching location");
|
2024-05-17 23:02:29 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
const res = await fetch(url);
|
|
|
|
if (!res.ok) {
|
|
|
|
console.error(`Fetch error: ${res.statusText}`);
|
2024-05-17 23:57:46 +00:00
|
|
|
return NextResponse.json(
|
|
|
|
{ error: "There was an error fetching the data" },
|
|
|
|
{ status: res.status }
|
|
|
|
);
|
2024-05-17 23:02:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const data: LocationType = await res.json();
|
|
|
|
if (!data.results[0]?.formatted_address) {
|
|
|
|
console.error("Unable to find the address in the response");
|
2024-05-17 23:57:46 +00:00
|
|
|
return NextResponse.json(
|
|
|
|
{ error: "Unable to find the address" },
|
|
|
|
{ status: 404 }
|
|
|
|
);
|
2024-05-17 23:02:29 +00:00
|
|
|
}
|
|
|
|
|
2024-05-17 23:57:46 +00:00
|
|
|
const locationData: coordType = {
|
2024-05-17 23:02:29 +00:00
|
|
|
name: data.results[0].formatted_address,
|
|
|
|
geo: data.results[0].geometry.location,
|
|
|
|
};
|
2024-05-17 23:57:46 +00:00
|
|
|
|
|
|
|
return NextResponse.json(locationData);
|
2024-05-17 23:02:29 +00:00
|
|
|
} catch (error) {
|
|
|
|
console.error("Error fetching location:", error);
|
2024-05-17 23:57:46 +00:00
|
|
|
return NextResponse.json(
|
|
|
|
{ error: "Error fetching location" },
|
|
|
|
{ status: 500 }
|
|
|
|
);
|
2024-05-17 22:54:39 +00:00
|
|
|
}
|
|
|
|
}
|