You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python实现Google Maps Places API多地理坐标批量查询?

实现批量调用Google Maps Places API查询多个地理坐标

很简单,咱们只需要把要查询的多个地理坐标整理成一个列表,然后通过循环逐个发起API请求,再把所有结果汇总写入CSV就可以了。我给你调整了代码,还加了一些实用的优化点,比如CSV表头、异常捕获(避免单个请求失败导致程序终止),以及更安全的文件操作方式:

import urllib.request
import json
import csv

# 基础配置
googleGeocodeUrl = "https://maps.googleapis.com/maps/api/place/textsearch/json?query="
keyword = "hospitales"
APIKEY = '&key='+'AIzaSyg5v17Ik'  # 注意:记得保护好你的API密钥,不要公开!
radius = 5000  # 搜索半径,统一设置在这里更方便修改

# 要批量查询的地理坐标列表,格式是(纬度, 经度)
locations_to_query = [
    (-12.135, -77.023),
    (-12.043, -77.029),
    (-11.987, -77.056)
    # 可以继续添加更多坐标
]

# 用with语句打开CSV文件,自动处理关闭操作,更安全
with open('hospitals.csv', 'w', newline='', encoding='utf-8') as export:
    csv_writer = csv.writer(export)
    # 写入CSV表头
    csv_writer.writerow(['名称', '经度', '纬度'])
    
    # 循环遍历每个地理坐标,发起请求
    for lat, lng in locations_to_query:
        # 构造当前坐标的location参数
        geolocation = f"&location={lat},{lng}&radius={radius}"
        # 拼接完整请求URL
        url = googleGeocodeUrl + keyword + geolocation + APIKEY
        
        try:
            # 发起API请求并解析响应
            json_response = urllib.request.urlopen(url)
            search = json_response.read().decode('utf-8')
            searchjson = json.loads(search)
            
            # 处理当前坐标返回的结果
            if 'results' in searchjson and searchjson['results']:
                for place in searchjson['results']:
                    place_name = place['name']
                    place_lng = place['geometry']['location']['lng']
                    place_lat = place['geometry']['location']['lat']
                    # 打印结果并写入CSV
                    print(f"坐标({lat}, {lng})找到:{place_name}")
                    csv_writer.writerow([place_name, place_lng, place_lat])
            else:
                print(f"坐标({lat}, {lng})没有找到匹配的结果")
                
        except Exception as e:
            print(f"处理坐标({lat}, {lng})时出错:{str(e)}")

关键说明:

  • 批量坐标列表:locations_to_query里可以添加任意多的(纬度, 经度)元组,循环会自动逐个处理
  • CSV优化:用csv.writer来处理写入,避免手动拼接字符串可能出现的格式问题(比如名称里有逗号的情况),同时添加了表头让CSV更易读
  • 异常处理:包裹了请求和解析的逻辑,就算某个坐标请求失败(比如网络问题、API返回错误),程序也会继续处理下一个坐标
  • API密钥安全:记得不要把你的API密钥公开到代码仓库或者公共场合,最好用环境变量来管理(比如os.getenv('GOOGLE_MAPS_API_KEY'))

内容的提问来源于stack exchange,提问作者Simon GIS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:38:18