From 6c5d2f191406c5b898e767ba1e647ecf19943ef2 Mon Sep 17 00:00:00 2001 From: itskovacs Date: Mon, 3 Nov 2025 18:49:48 +0100 Subject: [PATCH] retrieve boundaries of location from GMaps API --- backend/trip/routers/places.py | 16 +++++++++++++++- backend/trip/utils/gmaps.py | 23 +++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/backend/trip/routers/places.py b/backend/trip/routers/places.py index cf0f3ca..7ca82a2 100644 --- a/backend/trip/routers/places.py +++ b/backend/trip/routers/places.py @@ -11,7 +11,7 @@ from ..models.models import (Category, GooglePlaceResult, Image, Place, User) from ..security import verify_exists_and_owns from ..utils.gmaps import (compute_avg_price, compute_description, - gmaps_textsearch) + gmaps_get_boundaries, gmaps_textsearch) from ..utils.utils import (b64img_decode, download_file, patch_image, save_image_to_file) @@ -139,6 +139,20 @@ async def google_search_text( return results +@router.get("/google-geocode") +async def google_geocode_search( + q: str, session: SessionDep, current_user: Annotated[str, Depends(get_current_username)] +): + db_user = session.get(User, current_user) + if not db_user or not db_user.google_apikey: + raise HTTPException(status_code=400, detail="Google Maps API key not configured") + + bounds = await gmaps_get_boundaries(q, db_user.google_apikey) + if not bounds: + raise HTTPException(status_code=400, detail="Location not resolved by GMaps") + return bounds + + @router.put("/{place_id}", response_model=PlaceRead) def update_place( session: SessionDep, diff --git a/backend/trip/utils/gmaps.py b/backend/trip/utils/gmaps.py index 197ce65..0bacfcf 100644 --- a/backend/trip/utils/gmaps.py +++ b/backend/trip/utils/gmaps.py @@ -53,3 +53,26 @@ async def gmaps_textsearch(search: str, api_key: str) -> list[dict[str, Any]]: return data.get("places", []) except Exception: raise HTTPException(status_code=400, detail="Bad Request") + + +async def gmaps_get_boundaries(name: str, api_key: str) -> dict[str, Any] | None: + url = "https://maps.googleapis.com/maps/api/geocode/json" + params = {"address": name, "key": api_key} + + try: + async with httpx.AsyncClient(timeout=10.0) as client: + response = await client.get(url, params=params) + response.raise_for_status() + data = response.json() + + if data.get("status") != "OK" or not data.get("results"): + return None + + result = data["results"][0] + geometry = result.get("geometry", {}) + bounds = geometry.get("bounds") + if not bounds: + bounds = geometry.get("viewport") + return bounds + except Exception: + raise HTTPException(status_code=400, detail="Bad Request")