如何使用 Python 调用 Google Maps API

了解如何使用 Python 调用 Google Maps API,完成地址转坐标、地点搜索、商家位置数据采集,以及获取结构化 JSON 响应,支持 App、本地 SEO 和数据工作流。

talor ai
Last updated on
3 min read

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、市场研究、门店拓展分析和本地 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。本地 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,让数据之后仍然可用。

Scale Your Data
Operations Today.

Join the world's most robust proxy network.

Start Free Trial