import { NextRequest, NextResponse } from "next/server"; import { coordType, LocationType } from "@/types/types"; 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 } ); } const placesKey = process.env.PLACES_API; if (!placesKey) { console.error("PLACES_API environment variable is not set"); return NextResponse.json( { error: "PLACES_API environment variable is not set" }, { status: 500 } ); } const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${searchLocation}&key=${placesKey}`; console.log("Fetching location"); try { const res = await fetch(url); if (!res.ok) { console.error(`Fetch error: ${res.statusText}`); return NextResponse.json( { error: "There was an error fetching the data" }, { status: res.status } ); } const data: LocationType = await res.json(); if (!data.results[0]?.formatted_address) { console.error("Unable to find the address in the response"); return NextResponse.json( { error: "Unable to find the address" }, { status: 404 } ); } const locationData: coordType = { name: data.results[0].formatted_address, geo: data.results[0].geometry.location, }; return NextResponse.json(locationData); } catch (error) { console.error("Error fetching location:", error); return NextResponse.json( { error: "Error fetching location" }, { status: 500 } ); } }