retrieve boundaries of location from GMaps API

This commit is contained in:
itskovacs 2025-11-03 18:49:48 +01:00
parent d1463cea0d
commit 6c5d2f1914
2 changed files with 38 additions and 1 deletions

View File

@ -11,7 +11,7 @@ from ..models.models import (Category, GooglePlaceResult, Image, Place,
User) User)
from ..security import verify_exists_and_owns from ..security import verify_exists_and_owns
from ..utils.gmaps import (compute_avg_price, compute_description, 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, from ..utils.utils import (b64img_decode, download_file, patch_image,
save_image_to_file) save_image_to_file)
@ -139,6 +139,20 @@ async def google_search_text(
return results 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) @router.put("/{place_id}", response_model=PlaceRead)
def update_place( def update_place(
session: SessionDep, session: SessionDep,

View File

@ -53,3 +53,26 @@ async def gmaps_textsearch(search: str, api_key: str) -> list[dict[str, Any]]:
return data.get("places", []) return data.get("places", [])
except Exception: except Exception:
raise HTTPException(status_code=400, detail="Bad Request") 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")