# 指定地點 (https://nolantw.github.io/cwa/guides/locations/)

所有查詢函式都接受三種地點寫法。依需求選擇：

| 寫法 | 範例 | 適合 |
| --- | --- | --- |
| 地名 | `"臺北市信義區"`、`"左營區"` | 使用者輸入、快速測試 |
| 常數 | `Township.TAIPEI.XINYI`、`County.HUALIEN` | 程式中固定的地點，編輯器可自動完成 |
| 經緯度 | `Coordinates(latitude=25.034, longitude=121.5645)` | GPS 位置、地圖上的點 |

## 地名

地名可以使用全名，也可以使用不會混淆的簡稱。`台` 與 `臺` 視為相同：

```python
import cwa

cwa.weather.get("臺北市信義區")  # 全名
cwa.weather.get("台北市信義區")  # 台、臺皆可
cwa.weather.get("左營區")  # 只有高雄市有左營區
cwa.weather.get("花蓮市")
```

地名無法對應到唯一的鄉鎮時，會引發例外：

| 例外 | 情況 | 處理方式 |
| --- | --- | --- |
| `AmbiguousLocationError` | 簡稱對應多個鄉鎮，例如 `"中正區"` 同時符合臺北市及基隆市 | `error.candidates` 列出所有符合的全名，可讓使用者從中選擇 |
| `UnknownLocationError` | 找不到這個地名 | 確認拼寫，或改用常數 |

```python
try:
    cwa.weather.get("中正區")
except cwa.AmbiguousLocationError as error:
    print(error.candidates)  # ('基隆市中正區', '臺北市中正區')
```

## 常數

`County` 列出所有縣市，`Township` 依縣市列出所有鄉鎮。使用常數不會有拼寫錯誤，編輯器也能自動完成：

```python
from cwa import County, Township

xinyi = Township.TAIPEI.XINYI
print(xinyi.full_name)  # 臺北市信義區
print(xinyi.code)  # 行政區代碼
print(xinyi.county is County.TAIPEI)  # True

for town in County.HUALIEN.townships:
    print(town.name)
```

已有地名字串時，可用 `parse()` 轉成常數，規則與上方地名相同：

```python
town = Township.parse("高雄市左營區")
county = County.parse("花蓮縣")
```

## 經緯度

經緯度以 WGS84 十進位度數表示，也就是 GPS 及 Google 地圖使用的格式：

```python
from cwa import Coordinates

taipei_101 = Coordinates(latitude=25.034, longitude=121.5645)

reading = cwa.observations.nearest(taipei_101)
alerts = cwa.alerts.active(taipei_101)
```

並非所有功能都接受經緯度：

| 功能 | 地名或常數 | 經緯度 |
| --- | --- | --- |
| 預報、綜合天氣 | ✓ | ✗，預報以鄉鎮為單位 |
| 觀測值、測站 | ✓ | ✓ |
| 警特報 | ✓ | ✓，需安裝 `cwa[geo]` |
| 地震震央距離 | ✓ | ✓ |

以鄉鎮查詢觀測值或計算距離時，SDK 使用該鄉鎮的代表點 `Township.coordinates` 作為位置。