1
0
Fork 0
mirror of https://github.com/seanmorley15/AdventureLog.git synced 2025-07-19 12:59:36 +02:00

fix(geocoding): improve error handling and response validation in search_google function

This commit is contained in:
Sean Morley 2025-06-16 11:47:36 -04:00
parent cee9345bf1
commit 930c98a607
2 changed files with 58 additions and 39 deletions

View file

@ -6,47 +6,60 @@ from django.conf import settings
# ----------------- # -----------------
# SEARCHING # SEARCHING
# -----------------
def search_google(query): def search_google(query):
api_key = settings.GOOGLE_MAPS_API_KEY try:
url = "https://maps.googleapis.com/maps/api/place/textsearch/json" api_key = settings.GOOGLE_MAPS_API_KEY
params = {'query': query, 'key': api_key} if not api_key:
response = requests.get(url, params=params) return {"error": "Missing Google Maps API key"}
data = response.json()
results = [] url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
for r in data.get("results", []): params = {'query': query, 'key': api_key}
location = r.get("geometry", {}).get("location", {}) response = requests.get(url, params=params, timeout=(2, 5))
types = r.get("types", []) response.raise_for_status()
# First type is often most specific (e.g., 'restaurant', 'locality') data = response.json()
primary_type = types[0] if types else None if data.get("status") != "OK":
category = _extract_google_category(types) return {
addresstype = _infer_addresstype(primary_type) "error": f"Google Maps API error: {data.get('status')}",
"message": data.get("error_message", "")
}
importance = None results = []
if r.get("user_ratings_total") and r.get("rating"): for place in data.get("results", []):
# Simple importance heuristic based on popularity and quality location = place.get("geometry", {}).get("location", {})
importance = round(float(r["rating"]) * r["user_ratings_total"] / 100, 2) types = place.get("types", [])
primary_type = types[0] if types else None
category = _extract_google_category(types)
addresstype = _infer_addresstype(primary_type)
results.append({ importance = None
"lat": location.get("lat"), rating = place.get("rating")
"lon": location.get("lng"), ratings_total = place.get("user_ratings_total")
"name": r.get("name"), if rating is not None and ratings_total:
"display_name": r.get("formatted_address"), importance = round(float(rating) * ratings_total / 100, 2)
"type": primary_type,
"category": category,
"importance": importance,
"addresstype": addresstype,
"powered_by": "google",
})
# order by importance if available results.append({
if results and any("importance" in r for r in results): "lat": location.get("lat"),
results.sort(key=lambda x: x.get("importance", 0), reverse=True) "lon": location.get("lng"),
"name": place.get("name"),
"display_name": place.get("formatted_address"),
"type": primary_type,
"category": category,
"importance": importance,
"addresstype": addresstype,
"powered_by": "google",
})
return results if results:
results.sort(key=lambda r: r["importance"] if r["importance"] is not None else 0, reverse=True)
return results or {"error": "No results found"}
except requests.exceptions.RequestException as e:
return {"error": "Network error while contacting Google Maps", "details": str(e)}
except Exception as e:
return {"error": "Unexpected error during Google search", "details": str(e)}
def _extract_google_category(types): def _extract_google_category(types):
# Basic category inference based on common place types # Basic category inference based on common place types

View file

@ -172,12 +172,18 @@
} }
let res = await fetch(`/api/reverse-geocode/search/?query=${query}`); let res = await fetch(`/api/reverse-geocode/search/?query=${query}`);
console.log(res); console.log(res);
let data = (await res.json()) as GeocodeSearchResult[]; let data = (await res.json()) as GeocodeSearchResult[] | { error: string };
places = data;
if (data.length === 0) { if ('error' in data) {
places = [];
noPlaces = true; noPlaces = true;
} else { } else {
noPlaces = false; places = data;
if (data.length === 0) {
noPlaces = true;
} else {
noPlaces = false;
}
} }
} }