Create geocoding.py
Browse files- services/geocoding.py +42 -0
services/geocoding.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
from typing import Optional, Dict
|
| 3 |
+
import os
|
| 4 |
+
import requests
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
|
| 7 |
+
# Nominatimの利用規約に従ってUAと連絡先を付与
|
| 8 |
+
def _ua() -> Dict[str, str]:
|
| 9 |
+
email = os.getenv("GEOCODING_EMAIL") or os.getenv("CONTACT_EMAIL") or "example@example.com"
|
| 10 |
+
return {"User-Agent": f"HF-Space-Trip-Planner/1.0 (contact: {email})"}
|
| 11 |
+
|
| 12 |
+
@lru_cache(maxsize=512)
|
| 13 |
+
def geocode_city(city: str) -> Optional[Dict[str, object]]:
|
| 14 |
+
"""
|
| 15 |
+
文字列の都市名から緯度経度を取得(Nominatim / OpenStreetMap)。
|
| 16 |
+
成功時: {"lat": float, "lon": float, "display_name": str}
|
| 17 |
+
失敗時: None
|
| 18 |
+
"""
|
| 19 |
+
if not city or not str(city).strip():
|
| 20 |
+
return None
|
| 21 |
+
|
| 22 |
+
q = str(city).strip()
|
| 23 |
+
url = "https://nominatim.openstreetmap.org/search"
|
| 24 |
+
params = {
|
| 25 |
+
"q": q,
|
| 26 |
+
"format": "jsonv2",
|
| 27 |
+
"addressdetails": 1,
|
| 28 |
+
"limit": 1,
|
| 29 |
+
}
|
| 30 |
+
try:
|
| 31 |
+
r = requests.get(url, params=params, headers=_ua(), timeout=20)
|
| 32 |
+
r.raise_for_status()
|
| 33 |
+
items = r.json()
|
| 34 |
+
if not items:
|
| 35 |
+
return None
|
| 36 |
+
j = items[0]
|
| 37 |
+
lat = float(j["lat"])
|
| 38 |
+
lon = float(j["lon"])
|
| 39 |
+
name = j.get("display_name") or q
|
| 40 |
+
return {"lat": lat, "lon": lon, "display_name": name}
|
| 41 |
+
except Exception:
|
| 42 |
+
return None
|