maps_client.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  1. #!/usr/bin/env python3
  2. """
  3. maps_client.py - CLI tool for maps, geocoding, routing, POI search, and more.
  4. Uses only Python stdlib. Data from OpenStreetMap/Nominatim, Overpass API, OSRM,
  5. and TimeAPI.io.
  6. Commands:
  7. search - Geocode a place name to coordinates
  8. reverse - Reverse geocode coordinates to an address
  9. nearby - Find nearby POIs by category
  10. distance - Road distance and travel time between two places
  11. directions - Turn-by-turn directions between two places
  12. timezone - Timezone info for coordinates
  13. bbox - Find POIs within a bounding box
  14. area - Get bounding box and area info for a named place
  15. """
  16. import argparse
  17. import json
  18. import math
  19. import sys
  20. import time
  21. import urllib.error
  22. import urllib.parse
  23. import urllib.request
  24. # ---------------------------------------------------------------------------
  25. # Constants
  26. # ---------------------------------------------------------------------------
  27. USER_AGENT = "HermesAgent/1.0 (contact: hermes@agent.ai)"
  28. DATA_SOURCE = "OpenStreetMap/Nominatim"
  29. NOMINATIM_SEARCH = "https://nominatim.openstreetmap.org/search"
  30. NOMINATIM_REVERSE = "https://nominatim.openstreetmap.org/reverse"
  31. # Public Overpass endpoints. We try them in order so a single server
  32. # outage doesn't break the skill — kumi.systems is a well-known mirror.
  33. OVERPASS_URLS = [
  34. "https://overpass-api.de/api/interpreter",
  35. "https://overpass.kumi.systems/api/interpreter",
  36. ]
  37. # Backward-compat alias for any caller that imports OVERPASS_API directly.
  38. OVERPASS_API = OVERPASS_URLS[0]
  39. OSRM_BASE = "https://router.project-osrm.org/route/v1"
  40. TIMEAPI_BASE = "https://timeapi.io/api/timezone/coordinate"
  41. # Seconds to sleep between Nominatim requests (ToS requirement)
  42. NOMINATIM_RATE_LIMIT = 1.0
  43. # Maximum retries for HTTP errors
  44. MAX_RETRIES = 3
  45. RETRY_DELAY = 2.0 # seconds
  46. # Category -> (OSM tag key, OSM tag value)
  47. CATEGORY_TAGS = {
  48. # Food & Drink
  49. "restaurant": ("amenity", "restaurant"),
  50. "cafe": ("amenity", "cafe"),
  51. "bar": ("amenity", "bar"),
  52. # bakery is tagged as shop=bakery in the OSM wiki, but some mappers use
  53. # amenity=bakery. Search both so small indie bakeries aren't missed.
  54. "bakery": [("shop", "bakery"), ("amenity", "bakery")],
  55. "convenience_store": ("shop", "convenience"),
  56. # Health
  57. "hospital": ("amenity", "hospital"),
  58. "pharmacy": ("amenity", "pharmacy"),
  59. "dentist": ("amenity", "dentist"),
  60. "doctor": ("amenity", "doctors"),
  61. "veterinary": ("amenity", "veterinary"),
  62. # Accommodation
  63. "hotel": ("tourism", "hotel"),
  64. "guest_house": ("tourism", "guest_house"),
  65. "camp_site": ("tourism", "camp_site"),
  66. # Shopping & Services
  67. "supermarket": ("shop", "supermarket"),
  68. "bookshop": ("shop", "books"),
  69. "laundry": ("shop", "laundry"),
  70. # Finance
  71. "atm": ("amenity", "atm"),
  72. "bank": ("amenity", "bank"),
  73. # Transport
  74. "gas_station": ("amenity", "fuel"),
  75. "parking": ("amenity", "parking"),
  76. "airport": ("aeroway", "aerodrome"),
  77. "train_station": ("railway", "station"),
  78. "bus_stop": ("highway", "bus_stop"),
  79. "taxi": ("amenity", "taxi"),
  80. "car_wash": ("amenity", "car_wash"),
  81. "car_rental": ("amenity", "car_rental"),
  82. "bicycle_rental": ("amenity", "bicycle_rental"),
  83. # Culture & Entertainment
  84. "museum": ("tourism", "museum"),
  85. "cinema": ("amenity", "cinema"),
  86. "theatre": ("amenity", "theatre"),
  87. "nightclub": ("amenity", "nightclub"),
  88. "zoo": ("tourism", "zoo"),
  89. # Education
  90. "school": ("amenity", "school"),
  91. "university": ("amenity", "university"),
  92. "library": ("amenity", "library"),
  93. # Public Services
  94. "police": ("amenity", "police"),
  95. "fire_station": ("amenity", "fire_station"),
  96. "post_office": ("amenity", "post_office"),
  97. # Religion
  98. "church": ("amenity", "place_of_worship"), # refined by religion tag
  99. "mosque": ("amenity", "place_of_worship"),
  100. "synagogue": ("amenity", "place_of_worship"),
  101. # Recreation
  102. "park": ("leisure", "park"),
  103. "gym": ("leisure", "fitness_centre"),
  104. "swimming_pool": ("leisure", "swimming_pool"),
  105. "playground": ("leisure", "playground"),
  106. "stadium": ("leisure", "stadium"),
  107. }
  108. # Religion-specific overrides for place_of_worship categories
  109. RELIGION_FILTER = {
  110. "church": "christian",
  111. "mosque": "muslim",
  112. "synagogue": "jewish",
  113. }
  114. VALID_CATEGORIES = sorted(CATEGORY_TAGS.keys())
  115. def _tags_for(category):
  116. """Return the CATEGORY_TAGS entry as a list of (key, value) pairs.
  117. Most categories map to a single (tag_key, tag_val) tuple, but some
  118. (e.g. ``bakery``) are tagged under more than one OSM key and are
  119. represented as a list of tuples. Normalise both forms to a list.
  120. """
  121. entry = CATEGORY_TAGS[category]
  122. if isinstance(entry, list):
  123. return list(entry)
  124. return [entry]
  125. OSRM_PROFILES = {
  126. "driving": "driving",
  127. "walking": "foot",
  128. "cycling": "bike",
  129. }
  130. # ---------------------------------------------------------------------------
  131. # Output helpers
  132. # ---------------------------------------------------------------------------
  133. def print_json(data):
  134. """Print data as pretty-printed JSON to stdout."""
  135. print(json.dumps(data, indent=2, ensure_ascii=False))
  136. def error_exit(message, code=1):
  137. """Print an error result as JSON and exit."""
  138. print_json({"error": message, "status": "error"})
  139. sys.exit(code)
  140. # ---------------------------------------------------------------------------
  141. # HTTP helpers
  142. # ---------------------------------------------------------------------------
  143. def http_get(url, params=None, retries=MAX_RETRIES, silent=False):
  144. """
  145. Perform an HTTP GET request, returning parsed JSON.
  146. Adds the required User-Agent header. Retries on transient errors.
  147. If silent=True, raises RuntimeError instead of calling error_exit.
  148. """
  149. if params:
  150. url = url + "?" + urllib.parse.urlencode(params)
  151. req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
  152. last_error = None
  153. for attempt in range(1, retries + 1):
  154. try:
  155. with urllib.request.urlopen(req, timeout=15) as resp:
  156. raw = resp.read().decode("utf-8")
  157. return json.loads(raw)
  158. except urllib.error.HTTPError as exc:
  159. last_error = f"HTTP {exc.code}: {exc.reason} for {url}"
  160. if exc.code in {429, 503, 502, 504}:
  161. time.sleep(RETRY_DELAY * attempt)
  162. else:
  163. if silent:
  164. raise RuntimeError(last_error)
  165. error_exit(last_error)
  166. except urllib.error.URLError as exc:
  167. last_error = f"URL error: {exc.reason}"
  168. time.sleep(RETRY_DELAY * attempt)
  169. except json.JSONDecodeError as exc:
  170. last_error = f"JSON parse error: {exc}"
  171. time.sleep(RETRY_DELAY * attempt)
  172. msg = f"Request failed after {retries} attempts. Last error: {last_error}"
  173. if silent:
  174. raise RuntimeError(msg)
  175. error_exit(msg)
  176. def http_get_text(url, params=None, retries=MAX_RETRIES, silent=False):
  177. """
  178. Like http_get but returns raw text instead of parsed JSON.
  179. Useful for APIs that may return non-JSON responses.
  180. """
  181. if params:
  182. url = url + "?" + urllib.parse.urlencode(params)
  183. req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
  184. last_error = None
  185. for attempt in range(1, retries + 1):
  186. try:
  187. with urllib.request.urlopen(req, timeout=15) as resp:
  188. return resp.read().decode("utf-8")
  189. except urllib.error.HTTPError as exc:
  190. last_error = f"HTTP {exc.code}: {exc.reason} for {url}"
  191. if exc.code in {429, 503, 502, 504}:
  192. time.sleep(RETRY_DELAY * attempt)
  193. else:
  194. if silent:
  195. raise RuntimeError(last_error)
  196. error_exit(last_error)
  197. except urllib.error.URLError as exc:
  198. last_error = f"URL error: {exc.reason}"
  199. time.sleep(RETRY_DELAY * attempt)
  200. msg = f"Request failed after {retries} attempts. Last error: {last_error}"
  201. if silent:
  202. raise RuntimeError(msg)
  203. error_exit(msg)
  204. def http_post(url, data_str, retries=MAX_RETRIES):
  205. """
  206. Perform an HTTP POST with a plain-text body (for Overpass QL).
  207. Returns parsed JSON.
  208. """
  209. encoded = data_str.encode("utf-8")
  210. req = urllib.request.Request(
  211. url,
  212. data=encoded,
  213. headers={
  214. "User-Agent": USER_AGENT,
  215. "Content-Type": "application/x-www-form-urlencoded",
  216. },
  217. )
  218. last_error = None
  219. for attempt in range(1, retries + 1):
  220. try:
  221. with urllib.request.urlopen(req, timeout=30) as resp:
  222. raw = resp.read().decode("utf-8")
  223. return json.loads(raw)
  224. except urllib.error.HTTPError as exc:
  225. last_error = f"HTTP {exc.code}: {exc.reason}"
  226. if exc.code in {429, 503, 502, 504}:
  227. time.sleep(RETRY_DELAY * attempt)
  228. else:
  229. error_exit(last_error)
  230. except urllib.error.URLError as exc:
  231. last_error = f"URL error: {exc.reason}"
  232. time.sleep(RETRY_DELAY * attempt)
  233. except json.JSONDecodeError as exc:
  234. last_error = f"JSON parse error: {exc}"
  235. time.sleep(RETRY_DELAY * attempt)
  236. error_exit(f"POST failed after {retries} attempts. Last error: {last_error}")
  237. def overpass_query(query):
  238. """POST an Overpass QL query, trying each URL in OVERPASS_URLS in turn.
  239. A single public Overpass mirror can be rate-limited or down; trying the
  240. next mirror before giving up turns a flaky outage into a retry. Returns
  241. parsed JSON. Falls through to error_exit if every mirror fails.
  242. """
  243. post_data = "data=" + urllib.parse.quote(query)
  244. last_error = None
  245. for url in OVERPASS_URLS:
  246. try:
  247. return http_post(url, post_data, retries=1)
  248. except SystemExit:
  249. # error_exit inside http_post — keep trying the next mirror.
  250. last_error = f"mirror {url} exhausted retries"
  251. continue
  252. except Exception as exc:
  253. last_error = f"{url}: {exc}"
  254. continue
  255. error_exit(
  256. f"All Overpass mirrors failed. Last error: {last_error or 'unknown'}"
  257. )
  258. # ---------------------------------------------------------------------------
  259. # Geo math
  260. # ---------------------------------------------------------------------------
  261. def haversine_m(lat1, lon1, lat2, lon2):
  262. """Return distance in metres between two lat/lon points (Haversine)."""
  263. R = 6_371_000 # Earth mean radius in metres
  264. phi1 = math.radians(lat1)
  265. phi2 = math.radians(lat2)
  266. dphi = math.radians(lat2 - lat1)
  267. dlam = math.radians(lon2 - lon1)
  268. a = (math.sin(dphi / 2) ** 2
  269. + math.cos(phi1) * math.cos(phi2) * math.sin(dlam / 2) ** 2)
  270. return 2 * R * math.atan2(math.sqrt(a), math.sqrt(1 - a))
  271. # ---------------------------------------------------------------------------
  272. # Nominatim helpers
  273. # ---------------------------------------------------------------------------
  274. def nominatim_search(query, limit=5):
  275. """Geocode a free-text query. Returns list of result dicts."""
  276. params = {
  277. "q": query,
  278. "format": "json",
  279. "limit": limit,
  280. "addressdetails": 1,
  281. }
  282. time.sleep(NOMINATIM_RATE_LIMIT)
  283. return http_get(NOMINATIM_SEARCH, params=params)
  284. def nominatim_reverse(lat, lon):
  285. """Reverse geocode lat/lon. Returns a single result dict."""
  286. params = {
  287. "lat": lat,
  288. "lon": lon,
  289. "format": "json",
  290. "addressdetails": 1,
  291. }
  292. time.sleep(NOMINATIM_RATE_LIMIT)
  293. return http_get(NOMINATIM_REVERSE, params=params)
  294. def geocode_single(query):
  295. """
  296. Geocode a query and return (lat, lon, display_name).
  297. Exits with error if nothing found.
  298. """
  299. results = nominatim_search(query, limit=1)
  300. if not results:
  301. error_exit(f"Could not geocode: {query}")
  302. r = results[0]
  303. return float(r["lat"]), float(r["lon"]), r.get("display_name", query)
  304. # ---------------------------------------------------------------------------
  305. # Overpass helpers
  306. # ---------------------------------------------------------------------------
  307. def build_overpass_nearby(tag_key, tag_val, lat, lon, radius, limit,
  308. religion=None, tag_pairs=None):
  309. """Build an Overpass QL query for nearby POIs around a point.
  310. If ``tag_pairs`` is provided, the query unions across every
  311. ``(key, value)`` pair (used for categories like ``bakery`` that are
  312. tagged under more than one OSM key). Otherwise falls back to the
  313. single ``tag_key``/``tag_val`` pair for back-compat.
  314. """
  315. pairs = tag_pairs if tag_pairs else [(tag_key, tag_val)]
  316. religion_filter = ""
  317. if religion:
  318. religion_filter = f'["religion"="{religion}"]'
  319. body_lines = []
  320. for k, v in pairs:
  321. body_lines.append(
  322. f' node["{k}"="{v}"]{religion_filter}'
  323. f'(around:{radius},{lat},{lon});'
  324. )
  325. body_lines.append(
  326. f' way["{k}"="{v}"]{religion_filter}'
  327. f'(around:{radius},{lat},{lon});'
  328. )
  329. body = "\n".join(body_lines)
  330. return (
  331. f'[out:json][timeout:25];\n'
  332. f'(\n'
  333. f'{body}\n'
  334. f');\n'
  335. f'out center {limit};\n'
  336. )
  337. def build_overpass_bbox(tag_key, tag_val, south, west, north, east, limit,
  338. religion=None, tag_pairs=None):
  339. """Build an Overpass QL query for POIs within a bounding box.
  340. See ``build_overpass_nearby`` for ``tag_pairs`` semantics.
  341. """
  342. pairs = tag_pairs if tag_pairs else [(tag_key, tag_val)]
  343. religion_filter = ""
  344. if religion:
  345. religion_filter = f'["religion"="{religion}"]'
  346. body_lines = []
  347. for k, v in pairs:
  348. body_lines.append(
  349. f' node["{k}"="{v}"]{religion_filter}'
  350. f'({south},{west},{north},{east});'
  351. )
  352. body_lines.append(
  353. f' way["{k}"="{v}"]{religion_filter}'
  354. f'({south},{west},{north},{east});'
  355. )
  356. body = "\n".join(body_lines)
  357. return (
  358. f'[out:json][timeout:25];\n'
  359. f'(\n'
  360. f'{body}\n'
  361. f');\n'
  362. f'out center {limit};\n'
  363. )
  364. def parse_overpass_elements(elements, ref_lat=None, ref_lon=None):
  365. """
  366. Parse Overpass elements into a clean list of POI dicts.
  367. If ref_lat/ref_lon are provided, computes distance and sorts by it.
  368. """
  369. places = []
  370. for el in elements:
  371. # Ways have a "center" sub-dict; nodes have lat/lon directly
  372. if el["type"] == "way":
  373. center = el.get("center", {})
  374. el_lat = center.get("lat")
  375. el_lon = center.get("lon")
  376. else:
  377. el_lat = el.get("lat")
  378. el_lon = el.get("lon")
  379. if el_lat is None or el_lon is None:
  380. continue
  381. tags = el.get("tags", {})
  382. name = tags.get("name") or tags.get("name:en") or ""
  383. # Build a short address from available tags
  384. addr_parts = []
  385. for part_key in ("addr:housenumber", "addr:street", "addr:city"):
  386. val = tags.get(part_key)
  387. if val:
  388. addr_parts.append(val)
  389. address_str = ", ".join(addr_parts) if addr_parts else ""
  390. place = {
  391. "name": name,
  392. "address": address_str,
  393. "lat": el_lat,
  394. "lon": el_lon,
  395. "osm_type": el.get("type", ""),
  396. "osm_id": el.get("id", ""),
  397. # Clickable Google Maps link so the agent can render a tap-to-open
  398. # URL in chat without composing one downstream.
  399. "maps_url": f"https://www.google.com/maps/search/?api=1&query={el_lat},{el_lon}",
  400. "tags": {
  401. k: v for k, v in tags.items()
  402. if k not in {"name", "name:en",
  403. "addr:housenumber", "addr:street", "addr:city"}
  404. },
  405. }
  406. # Promote commonly-useful tags to top-level fields so agents can
  407. # reference them without digging into the raw ``tags`` dict.
  408. for src_key, dst_key in (
  409. ("cuisine", "cuisine"),
  410. ("opening_hours", "hours"),
  411. ("phone", "phone"),
  412. ("website", "website"),
  413. ):
  414. val = tags.get(src_key)
  415. if val:
  416. place[dst_key] = val
  417. if ref_lat is not None and ref_lon is not None:
  418. dist_m = haversine_m(ref_lat, ref_lon, el_lat, el_lon)
  419. place["distance_m"] = round(dist_m, 1)
  420. # With a reference point we can also hand back a directions URL.
  421. place["directions_url"] = (
  422. f"https://www.google.com/maps/dir/?api=1"
  423. f"&origin={ref_lat},{ref_lon}"
  424. f"&destination={el_lat},{el_lon}"
  425. )
  426. places.append(place)
  427. # Sort by distance if available
  428. if places and "distance_m" in places[0]:
  429. places.sort(key=lambda p: p["distance_m"])
  430. return places
  431. # ---------------------------------------------------------------------------
  432. # Command: search
  433. # ---------------------------------------------------------------------------
  434. def cmd_search(args):
  435. """Geocode a place name and return top results."""
  436. query = " ".join(args.query)
  437. raw = nominatim_search(query, limit=5)
  438. if not raw:
  439. print_json({
  440. "query": query,
  441. "results": [],
  442. "count": 0,
  443. "data_source": DATA_SOURCE,
  444. })
  445. return
  446. results = []
  447. for item in raw:
  448. bb = item.get("boundingbox", [])
  449. results.append({
  450. "name": item.get("name") or item.get("display_name", ""),
  451. "display_name": item.get("display_name", ""),
  452. "lat": float(item["lat"]),
  453. "lon": float(item["lon"]),
  454. "type": item.get("type", ""),
  455. "category": item.get("category", ""),
  456. "osm_type": item.get("osm_type", ""),
  457. "osm_id": item.get("osm_id", ""),
  458. "bounding_box": {
  459. "min_lat": float(bb[0]) if len(bb) > 0 else None,
  460. "max_lat": float(bb[1]) if len(bb) > 1 else None,
  461. "min_lon": float(bb[2]) if len(bb) > 2 else None,
  462. "max_lon": float(bb[3]) if len(bb) > 3 else None,
  463. },
  464. "importance": item.get("importance"),
  465. })
  466. print_json({
  467. "query": query,
  468. "results": results,
  469. "count": len(results),
  470. "data_source": DATA_SOURCE,
  471. })
  472. # ---------------------------------------------------------------------------
  473. # Command: reverse
  474. # ---------------------------------------------------------------------------
  475. def cmd_reverse(args):
  476. """Reverse geocode coordinates to a human-readable address."""
  477. try:
  478. lat = float(args.lat)
  479. lon = float(args.lon)
  480. except ValueError:
  481. error_exit("LAT and LON must be numeric values.")
  482. if not (-90 <= lat <= 90):
  483. error_exit("Latitude must be between -90 and 90.")
  484. if not (-180 <= lon <= 180):
  485. error_exit("Longitude must be between -180 and 180.")
  486. data = nominatim_reverse(lat, lon)
  487. if "error" in data:
  488. error_exit(f"Reverse geocode failed: {data['error']}")
  489. address = data.get("address", {})
  490. print_json({
  491. "lat": lat,
  492. "lon": lon,
  493. "display_name": data.get("display_name", ""),
  494. "address": {
  495. "house_number": address.get("house_number", ""),
  496. "road": address.get("road", ""),
  497. "neighbourhood": address.get("neighbourhood", ""),
  498. "suburb": address.get("suburb", ""),
  499. "city": (address.get("city")
  500. or address.get("town")
  501. or address.get("village", "")),
  502. "county": address.get("county", ""),
  503. "state": address.get("state", ""),
  504. "postcode": address.get("postcode", ""),
  505. "country": address.get("country", ""),
  506. "country_code": address.get("country_code", ""),
  507. },
  508. "osm_type": data.get("osm_type", ""),
  509. "osm_id": data.get("osm_id", ""),
  510. "data_source": DATA_SOURCE,
  511. })
  512. # ---------------------------------------------------------------------------
  513. # Command: nearby
  514. # ---------------------------------------------------------------------------
  515. def cmd_nearby(args):
  516. """Find nearby POIs using the Overpass API.
  517. Accepts either explicit coordinates (``lat``/``lon``) or a free-form
  518. address via ``--near`` (auto-geocoded through Nominatim). Supports
  519. multiple categories in one call — results are merged, deduplicated
  520. by ``osm_type+osm_id``, sorted by distance.
  521. """
  522. # Resolve the center point. --near takes precedence if provided so the
  523. # agent can ask "cafes near Times Square" in one command without having
  524. # to geocode first.
  525. if getattr(args, "near", None):
  526. near_query = " ".join(args.near).strip() if isinstance(args.near, list) else str(args.near).strip()
  527. if not near_query:
  528. error_exit("--near must be a non-empty address or place name.")
  529. lat, lon, _ = geocode_single(near_query)
  530. else:
  531. try:
  532. lat = float(args.lat)
  533. lon = float(args.lon)
  534. except (TypeError, ValueError):
  535. error_exit("Provide numeric LAT and LON, or use --near \"<address>\".")
  536. # Categories: support both legacy single positional ``category`` and the
  537. # new repeatable ``--category`` flag. Users can ask for multiple place
  538. # types in one query.
  539. categories = []
  540. if getattr(args, "category_list", None):
  541. categories.extend(args.category_list)
  542. if getattr(args, "category", None):
  543. categories.append(args.category)
  544. # Deduplicate, preserve order, lower-case.
  545. categories = list(dict.fromkeys(c.lower() for c in categories if c))
  546. if not categories:
  547. error_exit("Provide at least one category (positional or --category).")
  548. unknown = [c for c in categories if c not in CATEGORY_TAGS]
  549. if unknown:
  550. error_exit(
  551. f"Unknown categor{'ies' if len(unknown) > 1 else 'y'} "
  552. f"{', '.join(repr(c) for c in unknown)}. "
  553. f"Valid categories: {', '.join(VALID_CATEGORIES)}"
  554. )
  555. radius = int(args.radius)
  556. limit = int(args.limit)
  557. if radius <= 0:
  558. error_exit("Radius must be a positive integer (metres).")
  559. if limit <= 0:
  560. error_exit("Limit must be a positive integer.")
  561. # Query each category against the Overpass fallback chain, merge results,
  562. # dedupe by OSM identity so POIs tagged under multiple categories don't
  563. # appear twice.
  564. merged = {}
  565. for category in categories:
  566. tag_pairs = _tags_for(category)
  567. religion = RELIGION_FILTER.get(category)
  568. query = build_overpass_nearby(None, None, lat, lon, radius, limit,
  569. religion=religion, tag_pairs=tag_pairs)
  570. raw = overpass_query(query)
  571. elements = raw.get("elements", [])
  572. for place in parse_overpass_elements(elements, ref_lat=lat, ref_lon=lon):
  573. place["category"] = category
  574. key = (place.get("osm_type", ""), place.get("osm_id", ""))
  575. # Prefer the entry that actually has a distance_m attached (first
  576. # pass through the ref_lat/ref_lon branch), then first-seen wins.
  577. if key not in merged:
  578. merged[key] = place
  579. # Sort merged by distance when we have ref lat/lon, then cap at ``limit``.
  580. places = sorted(
  581. merged.values(),
  582. key=lambda p: p.get("distance_m", float("inf")),
  583. )[:limit]
  584. print_json({
  585. "center_lat": lat,
  586. "center_lon": lon,
  587. "categories": categories,
  588. "radius_m": radius,
  589. "count": len(places),
  590. "results": places,
  591. "data_source": DATA_SOURCE,
  592. })
  593. # ---------------------------------------------------------------------------
  594. # Command: distance
  595. # ---------------------------------------------------------------------------
  596. def cmd_distance(args):
  597. """Calculate road distance and travel time between two places."""
  598. origin_query = " ".join(args.origin)
  599. destination_query = " ".join(args.to)
  600. mode = args.mode.lower()
  601. if mode not in OSRM_PROFILES:
  602. error_exit(f"Invalid mode '{mode}'. Choose from: {', '.join(OSRM_PROFILES)}")
  603. # Geocode origin and destination
  604. o_lat, o_lon, o_name = geocode_single(origin_query)
  605. d_lat, d_lon, d_name = geocode_single(destination_query)
  606. profile = OSRM_PROFILES[mode]
  607. url = (
  608. f"{OSRM_BASE}/{profile}/"
  609. f"{o_lon},{o_lat};{d_lon},{d_lat}"
  610. f"?overview=false&steps=false"
  611. )
  612. osrm_data = http_get(url)
  613. if osrm_data.get("code") != "Ok":
  614. error_exit(
  615. f"OSRM routing failed: "
  616. f"{osrm_data.get('message', osrm_data.get('code', 'unknown error'))}"
  617. )
  618. routes = osrm_data.get("routes", [])
  619. if not routes:
  620. error_exit("No route found between the two locations.")
  621. route = routes[0]
  622. distance_m = route.get("distance", 0)
  623. duration_s = route.get("duration", 0)
  624. distance_km = round(distance_m / 1000, 3)
  625. duration_min = round(duration_s / 60, 2)
  626. # Straight-line distance for reference
  627. straight_m = haversine_m(o_lat, o_lon, d_lat, d_lon)
  628. print_json({
  629. "origin": {
  630. "query": origin_query,
  631. "display_name": o_name,
  632. "lat": o_lat,
  633. "lon": o_lon,
  634. },
  635. "destination": {
  636. "query": destination_query,
  637. "display_name": d_name,
  638. "lat": d_lat,
  639. "lon": d_lon,
  640. },
  641. "mode": mode,
  642. "distance_km": distance_km,
  643. "distance_m": round(distance_m, 1),
  644. "duration_minutes": duration_min,
  645. "duration_seconds": round(duration_s, 1),
  646. "straight_line_km": round(straight_m / 1000, 3),
  647. "data_source": DATA_SOURCE,
  648. })
  649. # ---------------------------------------------------------------------------
  650. # Command: directions
  651. # ---------------------------------------------------------------------------
  652. def _format_duration(seconds):
  653. """Format seconds into a human-readable string."""
  654. if seconds < 60:
  655. return f"{round(seconds)}s"
  656. minutes = seconds / 60
  657. if minutes < 60:
  658. return f"{round(minutes, 1)} min"
  659. hours = int(minutes // 60)
  660. remaining = round(minutes % 60)
  661. return f"{hours}h {remaining}min"
  662. def _format_distance(metres):
  663. """Format metres into a human-readable string."""
  664. if metres < 1000:
  665. return f"{round(metres)} m"
  666. return f"{round(metres / 1000, 2)} km"
  667. def cmd_directions(args):
  668. """Get turn-by-turn directions between two places via OSRM."""
  669. origin_query = " ".join(args.origin)
  670. destination_query = " ".join(args.to)
  671. mode = args.mode.lower()
  672. if mode not in OSRM_PROFILES:
  673. error_exit(f"Invalid mode '{mode}'. Choose from: {', '.join(OSRM_PROFILES)}")
  674. # Geocode origin and destination
  675. o_lat, o_lon, o_name = geocode_single(origin_query)
  676. d_lat, d_lon, d_name = geocode_single(destination_query)
  677. profile = OSRM_PROFILES[mode]
  678. url = (
  679. f"{OSRM_BASE}/{profile}/"
  680. f"{o_lon},{o_lat};{d_lon},{d_lat}"
  681. f"?overview=false&steps=true"
  682. )
  683. osrm_data = http_get(url)
  684. if osrm_data.get("code") != "Ok":
  685. error_exit(
  686. f"OSRM routing failed: "
  687. f"{osrm_data.get('message', osrm_data.get('code', 'unknown error'))}"
  688. )
  689. routes = osrm_data.get("routes", [])
  690. if not routes:
  691. error_exit("No route found between the two locations.")
  692. route = routes[0]
  693. distance_m = route.get("distance", 0)
  694. duration_s = route.get("duration", 0)
  695. # Extract steps from all legs
  696. steps = []
  697. step_num = 0
  698. for leg in route.get("legs", []):
  699. for step in leg.get("steps", []):
  700. maneuver = step.get("maneuver", {})
  701. step_dist = step.get("distance", 0)
  702. step_dur = step.get("duration", 0)
  703. step_name = step.get("name", "")
  704. modifier = maneuver.get("modifier", "")
  705. m_type = maneuver.get("type", "")
  706. # Build instruction text
  707. if m_type == "depart":
  708. instruction = f"Depart on {step_name}" if step_name else "Depart"
  709. elif m_type == "arrive":
  710. instruction = "Arrive at destination"
  711. elif m_type == "turn":
  712. instruction = f"Turn {modifier} onto {step_name}" if step_name else f"Turn {modifier}"
  713. elif m_type == "new name":
  714. instruction = f"Continue onto {step_name}" if step_name else "Continue"
  715. elif m_type == "merge":
  716. instruction = f"Merge {modifier} onto {step_name}" if step_name else f"Merge {modifier}"
  717. elif m_type == "fork":
  718. instruction = f"Take the {modifier} fork onto {step_name}" if step_name else f"Take the {modifier} fork"
  719. elif m_type == "roundabout":
  720. instruction = f"Enter roundabout, exit onto {step_name}" if step_name else "Enter roundabout"
  721. elif m_type == "rotary":
  722. instruction = f"Enter rotary, exit onto {step_name}" if step_name else "Enter rotary"
  723. elif m_type == "end of road":
  724. instruction = f"At end of road, turn {modifier} onto {step_name}" if step_name else f"At end of road, turn {modifier}"
  725. elif m_type == "continue":
  726. instruction = f"Continue {modifier} on {step_name}" if step_name else f"Continue {modifier}"
  727. elif m_type == "on ramp":
  728. instruction = f"Take ramp onto {step_name}" if step_name else "Take ramp"
  729. elif m_type == "off ramp":
  730. instruction = f"Take exit onto {step_name}" if step_name else "Take exit"
  731. else:
  732. instruction = f"{m_type} {modifier} {step_name}".strip()
  733. step_num += 1
  734. steps.append({
  735. "step": step_num,
  736. "instruction": instruction,
  737. "distance": _format_distance(step_dist),
  738. "distance_m": round(step_dist, 1),
  739. "duration": _format_duration(step_dur),
  740. "duration_s": round(step_dur, 1),
  741. "road_name": step_name,
  742. "maneuver": m_type,
  743. })
  744. print_json({
  745. "origin": {
  746. "query": origin_query,
  747. "display_name": o_name,
  748. "lat": o_lat,
  749. "lon": o_lon,
  750. },
  751. "destination": {
  752. "query": destination_query,
  753. "display_name": d_name,
  754. "lat": d_lat,
  755. "lon": d_lon,
  756. },
  757. "mode": mode,
  758. "total_distance": _format_distance(distance_m),
  759. "total_distance_m": round(distance_m, 1),
  760. "total_duration": _format_duration(duration_s),
  761. "total_duration_s": round(duration_s, 1),
  762. "steps": steps,
  763. "step_count": len(steps),
  764. "data_source": DATA_SOURCE,
  765. })
  766. # ---------------------------------------------------------------------------
  767. # Command: timezone
  768. # ---------------------------------------------------------------------------
  769. def cmd_timezone(args):
  770. """
  771. Get timezone information for a lat/lon coordinate.
  772. Strategy:
  773. 1. Try TimeAPI.io (free, no key, supports coordinate-based lookup).
  774. 2. Fallback: derive UTC offset approximation from longitude.
  775. """
  776. try:
  777. lat = float(args.lat)
  778. lon = float(args.lon)
  779. except ValueError:
  780. error_exit("LAT and LON must be numeric values.")
  781. if not (-90 <= lat <= 90):
  782. error_exit("Latitude must be between -90 and 90.")
  783. if not (-180 <= lon <= 180):
  784. error_exit("Longitude must be between -180 and 180.")
  785. timezone_str = None
  786. timezone_src = None
  787. current_time = None
  788. utc_offset = None
  789. # --- Strategy 1: TimeAPI.io coordinate lookup ---
  790. try:
  791. params = {"latitude": lat, "longitude": lon}
  792. tz_data = http_get(TIMEAPI_BASE, params=params, silent=True)
  793. if isinstance(tz_data, dict):
  794. timezone_str = tz_data.get("timeZone")
  795. current_time = tz_data.get("currentLocalTime")
  796. # Build utc_offset from currentUtcOffset if available
  797. offset_info = tz_data.get("currentUtcOffset", {})
  798. if isinstance(offset_info, dict):
  799. oh = offset_info.get("hours", 0)
  800. om = abs(offset_info.get("minutes", 0))
  801. os_ = offset_info.get("seconds", 0)
  802. sign = "+" if oh >= 0 else "-"
  803. utc_offset = f"{sign}{abs(oh):02d}:{om:02d}"
  804. if os_:
  805. utc_offset = f"{utc_offset}:{os_:02d}"
  806. elif tz_data.get("standardUtcOffset"):
  807. offset_info2 = tz_data["standardUtcOffset"]
  808. if isinstance(offset_info2, dict):
  809. oh = offset_info2.get("hours", 0)
  810. om = abs(offset_info2.get("minutes", 0))
  811. os_ = offset_info2.get("seconds", 0)
  812. sign = "+" if oh >= 0 else "-"
  813. utc_offset = f"{sign}{abs(oh):02d}:{om:02d}"
  814. if os_:
  815. utc_offset = f"{utc_offset}:{os_:02d}"
  816. timezone_src = "timeapi.io"
  817. except (RuntimeError, KeyError, TypeError):
  818. pass # API may be down; continue to fallback
  819. # --- Strategy 2: longitude-based UTC offset approximation ---
  820. if not timezone_str:
  821. approx_offset_h = round(lon / 15)
  822. if approx_offset_h >= 0:
  823. utc_offset = f"+{approx_offset_h:02d}:00"
  824. else:
  825. utc_offset = f"-{abs(approx_offset_h):02d}:00"
  826. timezone_str = f"UTC{utc_offset}"
  827. timezone_src = "longitude approximation (longitude/15)"
  828. print_json({
  829. "lat": lat,
  830. "lon": lon,
  831. "timezone": timezone_str,
  832. "utc_offset": utc_offset,
  833. "current_time": current_time,
  834. "source": timezone_src,
  835. "data_source": DATA_SOURCE,
  836. })
  837. # ---------------------------------------------------------------------------
  838. # Command: bbox
  839. # ---------------------------------------------------------------------------
  840. def cmd_bbox(args):
  841. """Find POIs within a bounding box using the Overpass API."""
  842. try:
  843. lat1 = float(args.lat1)
  844. lon1 = float(args.lon1)
  845. lat2 = float(args.lat2)
  846. lon2 = float(args.lon2)
  847. except ValueError:
  848. error_exit("All coordinate arguments must be numeric values.")
  849. # Normalize: south/west < north/east
  850. south = min(lat1, lat2)
  851. north = max(lat1, lat2)
  852. west = min(lon1, lon2)
  853. east = max(lon1, lon2)
  854. category = args.category.lower()
  855. if category not in CATEGORY_TAGS:
  856. error_exit(
  857. f"Unknown category '{category}'. "
  858. f"Valid categories: {', '.join(VALID_CATEGORIES)}"
  859. )
  860. limit = int(args.limit)
  861. if limit <= 0:
  862. error_exit("Limit must be a positive integer.")
  863. tag_pairs = _tags_for(category)
  864. religion = RELIGION_FILTER.get(category)
  865. query = build_overpass_bbox(None, None, south, west, north, east,
  866. limit, religion=religion, tag_pairs=tag_pairs)
  867. raw = overpass_query(query)
  868. elements = raw.get("elements", [])
  869. # Use center of bbox as reference for distance sorting
  870. center_lat = (south + north) / 2
  871. center_lon = (west + east) / 2
  872. places = parse_overpass_elements(elements, ref_lat=center_lat,
  873. ref_lon=center_lon)
  874. for p in places:
  875. p["category"] = category
  876. print_json({
  877. "bounding_box": {
  878. "south": south,
  879. "west": west,
  880. "north": north,
  881. "east": east,
  882. },
  883. "category": category,
  884. "count": len(places),
  885. "results": places,
  886. "data_source": DATA_SOURCE,
  887. })
  888. # ---------------------------------------------------------------------------
  889. # Command: area
  890. # ---------------------------------------------------------------------------
  891. def cmd_area(args):
  892. """Get bounding box and area info for a named place."""
  893. query = " ".join(args.place)
  894. raw = nominatim_search(query, limit=1)
  895. if not raw:
  896. error_exit(f"Could not find place: {query}")
  897. item = raw[0]
  898. bb = item.get("boundingbox", [])
  899. if len(bb) < 4:
  900. error_exit(f"No bounding box data available for: {query}")
  901. min_lat = float(bb[0])
  902. max_lat = float(bb[1])
  903. min_lon = float(bb[2])
  904. max_lon = float(bb[3])
  905. # Approximate area in km² using the bounding box
  906. # Width in km at the average latitude
  907. avg_lat = (min_lat + max_lat) / 2
  908. height_km = haversine_m(min_lat, min_lon, max_lat, min_lon) / 1000
  909. width_km = haversine_m(avg_lat, min_lon, avg_lat, max_lon) / 1000
  910. approx_area_km2 = round(height_km * width_km, 3)
  911. print_json({
  912. "query": query,
  913. "display_name": item.get("display_name", ""),
  914. "lat": float(item["lat"]),
  915. "lon": float(item["lon"]),
  916. "type": item.get("type", ""),
  917. "category": item.get("category", ""),
  918. "bounding_box": {
  919. "south": min_lat,
  920. "north": max_lat,
  921. "west": min_lon,
  922. "east": max_lon,
  923. },
  924. "dimensions": {
  925. "width_km": round(width_km, 3),
  926. "height_km": round(height_km, 3),
  927. },
  928. "approx_area_km2": approx_area_km2,
  929. "osm_type": item.get("osm_type", ""),
  930. "osm_id": item.get("osm_id", ""),
  931. "data_source": DATA_SOURCE,
  932. })
  933. # ---------------------------------------------------------------------------
  934. # CLI setup
  935. # ---------------------------------------------------------------------------
  936. def build_parser():
  937. parser = argparse.ArgumentParser(
  938. prog="maps_client.py",
  939. description=(
  940. "CLI maps tool: geocoding, reverse geocoding, POI search, "
  941. "routing, directions, timezone, and area lookup. "
  942. "Powered by OpenStreetMap, OSRM, Overpass, and TimeAPI.io. "
  943. "No API keys required."
  944. ),
  945. formatter_class=argparse.RawDescriptionHelpFormatter,
  946. epilog=(
  947. "Examples:\n"
  948. " maps_client.py search Times Square\n"
  949. " maps_client.py reverse 40.758 -73.985\n"
  950. " maps_client.py nearby 40.758 -73.985 restaurant --radius 800\n"
  951. " maps_client.py distance New York --to Los Angeles --mode driving\n"
  952. " maps_client.py directions Paris --to Berlin --mode driving\n"
  953. " maps_client.py timezone 48.8566 2.3522\n"
  954. " maps_client.py bbox 40.70 -74.02 40.78 -73.95 restaurant\n"
  955. " maps_client.py area Manhattan"
  956. ),
  957. )
  958. sub = parser.add_subparsers(dest="command", required=True,
  959. metavar="COMMAND")
  960. # -- search --
  961. p_search = sub.add_parser(
  962. "search",
  963. help="Geocode a place name to coordinates.",
  964. description="Search for a place by name and return coordinates and details.",
  965. )
  966. p_search.add_argument(
  967. "query", nargs="+",
  968. help="Place name or address to search.",
  969. )
  970. # -- reverse --
  971. p_reverse = sub.add_parser(
  972. "reverse",
  973. help="Reverse geocode coordinates to an address.",
  974. description="Convert latitude/longitude coordinates to a human-readable address.",
  975. )
  976. p_reverse.add_argument("lat", help="Latitude (decimal degrees).")
  977. p_reverse.add_argument("lon", help="Longitude (decimal degrees).")
  978. # -- nearby --
  979. p_nearby = sub.add_parser(
  980. "nearby",
  981. help="Find nearby places of a given category.",
  982. description=(
  983. "Find points of interest near a location using the Overpass API.\n"
  984. "Provide either LAT/LON, or use --near \"<address>\" to auto-geocode.\n"
  985. "Categories can be specified positionally OR repeated via --category\n"
  986. "to merge multiple types in one query (e.g. --category bar --category cafe).\n"
  987. f"Categories: {', '.join(VALID_CATEGORIES)}"
  988. ),
  989. formatter_class=argparse.RawDescriptionHelpFormatter,
  990. )
  991. p_nearby.add_argument(
  992. "lat", nargs="?", default=None,
  993. help="Center latitude (decimal degrees). Omit if using --near.",
  994. )
  995. p_nearby.add_argument(
  996. "lon", nargs="?", default=None,
  997. help="Center longitude (decimal degrees). Omit if using --near.",
  998. )
  999. p_nearby.add_argument(
  1000. "category", nargs="?", default=None,
  1001. help="POI category (use --help for full list). Omit if using --category flags.",
  1002. )
  1003. p_nearby.add_argument(
  1004. "--near", nargs="+", metavar="PLACE",
  1005. help="Address, city, or landmark to search around (geocoded via Nominatim).",
  1006. )
  1007. p_nearby.add_argument(
  1008. "--category", action="append", dest="category_list", default=[],
  1009. metavar="CAT",
  1010. help="POI category (repeatable — adds a type to the search).",
  1011. )
  1012. p_nearby.add_argument(
  1013. "--radius", "-r",
  1014. default=500, type=int, metavar="METRES",
  1015. help="Search radius in metres (default: 500).",
  1016. )
  1017. p_nearby.add_argument(
  1018. "--limit", "-n",
  1019. default=10, type=int, metavar="N",
  1020. help="Maximum number of results (default: 10).",
  1021. )
  1022. # -- distance --
  1023. p_dist = sub.add_parser(
  1024. "distance",
  1025. help="Calculate road distance and travel time.",
  1026. description=(
  1027. "Calculate road distance and estimated travel time between two places.\n"
  1028. "Example: maps_client.py distance New York --to Los Angeles"
  1029. ),
  1030. formatter_class=argparse.RawDescriptionHelpFormatter,
  1031. )
  1032. p_dist.add_argument(
  1033. "origin", nargs="+",
  1034. help="Origin address or place name.",
  1035. )
  1036. p_dist.add_argument(
  1037. "--to", nargs="+", required=True, metavar="DEST",
  1038. help="Destination address or place name (required).",
  1039. )
  1040. p_dist.add_argument(
  1041. "--mode", "-m",
  1042. default="driving",
  1043. choices=list(OSRM_PROFILES.keys()),
  1044. help="Travel mode (default: driving).",
  1045. )
  1046. # -- directions --
  1047. p_dir = sub.add_parser(
  1048. "directions",
  1049. help="Get turn-by-turn directions between two places.",
  1050. description=(
  1051. "Get step-by-step navigation directions between two places.\n"
  1052. "Example: maps_client.py directions Paris --to Berlin --mode driving"
  1053. ),
  1054. formatter_class=argparse.RawDescriptionHelpFormatter,
  1055. )
  1056. p_dir.add_argument(
  1057. "origin", nargs="+",
  1058. help="Origin address or place name.",
  1059. )
  1060. p_dir.add_argument(
  1061. "--to", nargs="+", required=True, metavar="DEST",
  1062. help="Destination address or place name (required).",
  1063. )
  1064. p_dir.add_argument(
  1065. "--mode", "-m",
  1066. default="driving",
  1067. choices=list(OSRM_PROFILES.keys()),
  1068. help="Travel mode (default: driving).",
  1069. )
  1070. # -- timezone --
  1071. p_tz = sub.add_parser(
  1072. "timezone",
  1073. help="Get timezone information for coordinates.",
  1074. description="Look up timezone and current local time for a lat/lon coordinate.",
  1075. )
  1076. p_tz.add_argument("lat", help="Latitude (decimal degrees).")
  1077. p_tz.add_argument("lon", help="Longitude (decimal degrees).")
  1078. # -- bbox --
  1079. p_bbox = sub.add_parser(
  1080. "bbox",
  1081. help="Find POIs within a bounding box.",
  1082. description=(
  1083. "Search for points of interest within a geographic bounding box.\n"
  1084. "Tip: use the 'area' command to find bounding boxes for named places.\n"
  1085. f"Categories: {', '.join(VALID_CATEGORIES)}"
  1086. ),
  1087. formatter_class=argparse.RawDescriptionHelpFormatter,
  1088. )
  1089. p_bbox.add_argument("lat1", help="First corner latitude.")
  1090. p_bbox.add_argument("lon1", help="First corner longitude.")
  1091. p_bbox.add_argument("lat2", help="Second corner latitude.")
  1092. p_bbox.add_argument("lon2", help="Second corner longitude.")
  1093. p_bbox.add_argument("category", help="POI category to search for.")
  1094. p_bbox.add_argument(
  1095. "--limit", "-n",
  1096. default=20, type=int, metavar="N",
  1097. help="Maximum number of results (default: 20).",
  1098. )
  1099. # -- area --
  1100. p_area = sub.add_parser(
  1101. "area",
  1102. help="Get bounding box and area info for a named place.",
  1103. description=(
  1104. "Look up a place by name and return its bounding box, dimensions, "
  1105. "and approximate area. Useful as input to the 'bbox' command."
  1106. ),
  1107. )
  1108. p_area.add_argument(
  1109. "place", nargs="+",
  1110. help="Place name to look up (e.g., 'Manhattan' or 'downtown Seattle').",
  1111. )
  1112. return parser
  1113. def main():
  1114. parser = build_parser()
  1115. args = parser.parse_args()
  1116. dispatch = {
  1117. "search": cmd_search,
  1118. "reverse": cmd_reverse,
  1119. "nearby": cmd_nearby,
  1120. "distance": cmd_distance,
  1121. "directions": cmd_directions,
  1122. "timezone": cmd_timezone,
  1123. "bbox": cmd_bbox,
  1124. "area": cmd_area,
  1125. }
  1126. handler = dispatch.get(args.command)
  1127. if handler is None:
  1128. error_exit(f"Unknown command: {args.command}")
  1129. handler(args)
  1130. if __name__ == "__main__":
  1131. main()