如何替换硬编码地址为CSV读取数据 用谷歌地图API批量计算距离
代码修改实现方案
核心改动如下:
- 引入Python内置
csv模块读取CSV文件地址,替换原代码中的硬编码destinations列表 - 新增通行时间(分钟)提取逻辑,同步输出公里单位的距离结果
- 增加基础异常捕获,避免单条地址解析/请求失败导致整个程序终止
- 支持将最终结果写入新CSV文件,方便后续整理使用
import urllib.request import urllib.error import json import csv # 谷歌地图Directions API配置 endpoint = 'https://maps.googleapis.com/maps/api/directions/json?' api_key = '替换为你自己的谷歌API密钥' # 基准固定地址,替换为你需要计算距离的固定地址 origin = '替换为实际基准地址,例如:1280 Main Street Hamilton ON'.replace(' ', '+') # CSV相关配置 csv_file_path = '替换为你的地址CSV文件实际路径,例如:./addresses.csv' address_column_name = 'address' # 替换为你的CSV中存储地址的列名 result_output_path = './distance_result.csv' # 计算结果输出路径 result_list = [] # 读取CSV中所有地址 with open(csv_file_path, 'r', encoding='utf-8') as f: reader = csv.DictReader(f) destinations = [row[address_column_name].strip() for row in reader if row[address_column_name].strip()] # 遍历计算每个地址的距离和通行时间 for idx, dest in enumerate(destinations): print(f"正在处理第{idx+1}/{len(destinations)}条地址:{dest}") try: current_dest = dest.replace(' ', '+') # 构造API请求 nav_request = f'origin={origin}&destination={current_dest}&key={api_key}' # 如需修改通行方式可新增mode参数,例如&mode=walking,默认是驾车 request_url = endpoint + nav_request # 发送请求并解析返回结果 response = urllib.request.urlopen(request_url, timeout=10).read() directions = json.loads(response) if directions.get('status') == 'OK' and directions.get('routes'): leg = directions["routes"][0]["legs"][0] distance_km = leg["distance"]["text"] # 接口返回时间单位为秒,转换为分钟取整 duration_min = round(leg["duration"]["value"] / 60) result_list.append({ "地址": dest, "通行距离": distance_km, "通行时间(分钟)": duration_min }) else: result_list.append({ "地址": dest, "通行距离": "解析失败", "通行时间(分钟)": "解析失败" }) except Exception as e: result_list.append({ "地址": dest, "通行距离": "请求失败", "通行时间(分钟)": "请求失败" }) # 结果写入CSV文件 with open(result_output_path, 'w', encoding='utf-8-sig', newline='') as f: writer = csv.DictWriter(f, fieldnames=["地址", "通行距离", "通行时间(分钟)"]) writer.writeheader() writer.writerows(result_list) # 控制台打印结果 print("处理完成,结果如下:") for res in result_list: print(f"{res['地址']} | 距离:{res['通行距离']} | 时间:{res['通行时间(分钟)']}分钟")
注意事项
- 请确保你的谷歌云账号已开通Directions API服务,且有足够的请求配额,1800次请求会产生对应费用,请提前确认
- 如果你的CSV文件编码不是UTF-8,可以修改
open方法中的encoding参数,例如改为gbk - 如需调整通行方式,可在请求参数中新增
mode参数,可选值为driving(驾车默认)、walking(步行)、bicycling(骑行)、transit(公共交通)
内容的提问来源于stack exchange,提问作者Chadi N
相关产品推荐
相关产品推荐

