如何使用 Python 調用 Google Maps API

了解如何使用 Python 調用 Google Maps API,完成地址轉座標、地點搜尋、商家位置資料收集,以及取得結構化 JSON 回應,支援 App、本地 SEO 和資料工作流程。

talor ai
最后更新于
3 分钟阅读

Google Maps 資料很適合用在地址解析、座標定位、地點搜尋、商家資料、路線規劃和位置型應用中。

使用 Python,你可以在 server side 調用 Google Maps APIs,取得結構化 JSON response,並把資料接入 dashboard、內部工具、本地搜尋流程或 AI 系統。

這篇文章用實用方式說明如何使用 Python 調用 Google Maps API,包括地址轉座標和 Places API 地點搜尋。

「Google Maps API」實際指什麼?

很多人會把不同服務都叫作 Google Maps API,但 Google Maps Platform 其實包含多個 APIs 和 SDKs。對 Python server-side 使用來說,常見選項包括 Geocoding API、Places API、Directions API、Distance Matrix API、Time Zone API 等 web services。Google 也提供 Java、Python、Go、Node.js client libraries,方便在 server side 使用 Google Maps web services。

常見任務可以這樣選:

任務

適合 API

地址轉經緯度

Geocoding API

按關鍵字搜尋地點

Places API Text Search

搜尋附近商家

Places API Nearby Search

取得地點詳情

Places API Place Details

計算路線或距離

Routes / Directions 相關 API

在前端顯示地圖

Maps JavaScript API

開始前,你需要建立已啟用 billing 的 Google Cloud project、啟用需要的 API,並產生 API key。Google getting-started 文件說明,API key 用於驗證請求和追蹤用量,正式環境中也應限制 API key。

準備工作

安裝 Python 套件:

pip install googlemaps requests python-dotenv

把 API key 存成環境變數:

export GOOGLE_MAPS_API_KEY="YOUR_API_KEY"

Windows PowerShell:

setx GOOGLE_MAPS_API_KEY "YOUR_API_KEY"

不要把 API key 寫死在公開程式碼中。正式專案應放在 server side,並在 Google Cloud Console 中設定限制。

範例 1:用 Python 將地址轉成座標

Geocoding 可以把可讀地址轉成 latitude 和 longitude。Google Geocoding API 用於將地址或 Place ID 轉成地理座標,也可以反向轉換。

import os
import googlemaps

api_key = os.environ["GOOGLE_MAPS_API_KEY"]
gmaps = googlemaps.Client(key=api_key)

address = "1600 Amphitheatre Parkway, Mountain View, CA"

results = gmaps.geocode(address)

if not results:
    print("No results found")
else:
    first = results[0]
    location = first["geometry"]["location"]

    print({
        "formatted_address": first["formatted_address"],
        "latitude": location["lat"],
        "longitude": location["lng"],
        "place_id": first["place_id"]
    })

可能得到:

{
  "formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
  "latitude": 37.4223878,
  "longitude": -122.0841877,
  "place_id": "ChIJ..."
}

這類資料可用於門店定位、配送範圍、地址校驗、房產工具、物流 dashboard 和本地商家匹配。

範例 2:用 Places API Text Search 搜尋地點

如果你想搜尋商家或 points of interest,可以使用 Places API。Google Places API 接受 HTTP requests,並返回 establishments、geographic locations 或 points of interest 的格式化地點資料。

新版 Text Search API 可以根據文字查詢尋找地點,例如 “pizza in New York”。Google 文件也說明,Text Search 需要 textQuery,並需要用 FieldMask 指定要返回哪些欄位。

import os
import json
import requests

api_key = os.environ["GOOGLE_MAPS_API_KEY"]

url = "https://places.googleapis.com/v1/places:searchText"

headers = {
    "Content-Type": "application/json",
    "X-Goog-Api-Key": api_key,
    "X-Goog-FieldMask": (
        "places.displayName,"
        "places.formattedAddress,"
        "places.location,"
        "places.rating,"
        "places.userRatingCount,"
        "places.googleMapsUri,"
        "places.websiteUri"
    )
}

payload = {
    "textQuery": "coffee shops in Seattle",
    "languageCode": "en"
}

response = requests.post(url, headers=headers, json=payload, timeout=30)
response.raise_for_status()

data = response.json()

for place in data.get("places", []):
    print(json.dumps({
        "name": place.get("displayName", {}).get("text"),
        "address": place.get("formattedAddress"),
        "rating": place.get("rating"),
        "reviews": place.get("userRatingCount"),
        "maps_url": place.get("googleMapsUri"),
        "website": place.get("websiteUri"),
        "location": place.get("location")
    }, indent=2))

可能得到:

{
  "name": "Example Coffee",
  "address": "123 Example St, Seattle, WA",
  "rating": 4.6,
  "reviews": 842,
  "maps_url": "https://maps.google.com/?cid=...",
  "website": "https://examplecoffee.com",
  "location": {
    "latitude": 47.609,
    "longitude": -122.333
  }
}

這類資料可以支援本地商家目錄、位置型 App、市場研究、門店拓展分析和 Local SEO 流程。

常見請求參數

使用 Python 調用 Google Maps APIs 時,常見控制項包括:

參數

為什麼重要

Query / textQuery

定義搜尋內容

Location

指定城市、國家或座標區域

Language

控制回應語言

Field mask

限制返回欄位和 response size

Place ID

穩定識別特定地點

Radius / bounding area

適合 nearby search

API key

用於請求驗證

對 Places API 來說,field mask 尤其重要。不要在只需要名稱、地址、座標、評分和網站時請求所有欄位。

什麼時候 Google Maps API 不夠用?

Google Maps APIs 很適合 place lookup、geocoding、place details 和 location-based app features。

但如果你的目標是追蹤 Google Maps 或 local results 在搜尋中如何出現,可能需要 local SERP API 或 map results API。Local SEO 團隊通常關心的不只是地點是否存在,而是 ranking position、query、market、timestamp 和 competitor visibility。

你可以用 SerpApi、SearchAPI、Bright Data 或 Talordata(注册成功後即可免費測試1000次API響應)這類工具測試這個流程。真正重要的是 response 是否包含乾淨欄位,例如 business name、address、rating、review count、ranking position、query、location 和 timestamp,讓 SEO 工具或 AI workflow 可以直接使用。

最佳實踐

不要把 API key 放在前端程式碼中,除非它已被正確限制用於瀏覽器環境。

Backend 專案應使用環境變數或 secret manager。

只請求真正需要的欄位。較小的 response 更容易解析和維護。

每條結果都應保存搜尋上下文:query、location、language、必要時的 device,以及 timestamp。

為 timeout、empty results 和 quota-related errors 加入錯誤處理。

穩定資料可以 cache,避免同樣查詢過度重複請求。

正式環境中,應在 Google Cloud Console 監控 usage 和 billing。Google Maps Platform 提供 billing 和 usage 工具,幫助檢查月度成本和節省情況。

結語

使用 Python 調用 Google Maps API 並不複雜,關鍵是選對 API。

地址轉座標用 Geocoding API;搜尋商家或地點用 Places API;計算路線或時間使用 routes 相關 API;如果目標是搜尋可見度、本地排名或競品監測,則應考慮 local SERP API。

真正重要的不只是發起 API request,而是建立乾淨的資料流程:定義 query、設定 location、只請求需要的欄位、保存結構化 JSON,並保留足夠 metadata,讓資料之後仍然可用。

立即开展您的数据业务

加入全球最强大的代理网络

免费试用