今天來完善 AI 行程規劃的 Google 地圖部分,當 Agent 規劃出景點後,要呼叫 Google Map API 將景點經緯度之類的資訊給 App 顯示,所以要來實作呼叫 API 的邏輯。
首先要開啟 Google Maps Platform 內的 API 服務,依照我的需求 Gemini 建議開啟 Geocoding API
以及 Places API
,用於經緯度查詢以及景點查詢,接著建立一組 API Key 供呼叫使用就好。
那就趕快來實作看看:
API_KEY=AIzaSyBawLaLHlB80Y1-i4H6r88CpQtRlF3Vhoo
curl -X POST -d '{
"textQuery" : "日月潭水社碼頭商店街"
}' \
-H 'Content-Type: application/json' -H "X-Goog-Api-Key: $API_KEY" \
-H 'X-Goog-FieldMask: *' \
'https://places.googleapis.com/v1/places:searchText'
curl -X GET -H 'Content-Type: application/json' \
-H "X-Goog-Api-Key: $API_KEY" \
-H "X-Goog-FieldMask: *" \
https://places.googleapis.com/v1/places/ChIJu123aQ7WaDQRmiZQuTKv0IU
有個 Header 是 X-Goog-FieldMask
是用來過濾需要的資料用,先使用 *
把資料存到本地慢慢看要留那些
規劃上應該是先用 Text Search 取得地點的 ID 後交給 Place Details 取得資訊來減少 API 呼叫時間和省錢,要新增的欄位有經緯度資訊和 Google Map 地圖連結,所以從 API Server 回傳的欄位要加上 "latlng" 和 "placeUri":
{
activities: [
{
...
placeUri: "string"
latLng: {
latitude: double,
longitude: double,
}
...
}
]
}
接著要實作呼叫 Google Map API 來完成需求,邏輯如下:
實作出來的扣很短,大概是這樣:
def get_detail_by_google_map(location: str) -> dict:
GOOGLEMAP_KEY = os.environ.get('GOOGLEMAP_KEY')
textsearch_url = 'https://places.googleapis.com/v1/places:searchText'
payload = {'textQuery': location}
headers = {
'X-Goog-Api-Key': GOOGLEMAP_KEY,
'X-Goog-FieldMask': 'places.id',
}
resp = requests.post(textsearch_url, json=payload, headers=headers)
if not resp.ok:
return {'latLng': None}
data = resp.json()
place = random.choice(data['places'])
detail_url = f'https://places.googleapis.com/v1/places/{place["id"]}'
headers = {
'X-Goog-Api-Key': GOOGLEMAP_KEY,
'X-Goog-FieldMask': (
'location,'
'regularOpeningHours,'
'displayName,'
'googleMapsLinks.placeUri'
),
}
resp = requests.get(detail_url, headers=headers)
if not resp.ok:
return {'latLng': None}
data = resp.json()
return {
'latLng': data['location'],
'placeUri': data['googleMapsLinks']['placeUri'],
}
為了讓 Agent 執行,要多下個指令讓它知道經緯度和網址要從 get_detail_by_google_map
函數取得:
- Retrieve the values of "latLng" and "placeUri" using the get_detail_by_google_map tool.
設定好後執行看看:
{
"title": "日月潭兩天一夜行程",
"activities": [
...
{
"type": "restaurant",
"location": "伊達邵碼頭周邊餐廳",
"startTime": "2025-09-10T13:00:00Z",
"duration": 60,
"endTime": "2025-09-10T14:00:00Z",
"note": "享用午餐",
"placeUri": "https://maps.google.com/?cid=9949215165815081704&g_mp=CiVnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLkdldFBsYWNlEAAYBCAA",
"latLng": {
"latitude": 23.8495186,
"longitude": 120.9328491
}
},
...
順利的取得經緯度和網址,明天再繼續把 API Server 串起來。