使用Google Maps Directions Layer批量请求触发OVER_QUERY_LIMIT求助
解决Google Maps Directions API请求超限问题
我看你遇到的问题核心在于gmaps的directions_layer是在前端(Jupyter的JavaScript环境)发起API请求,而你在Python代码里加的time.sleep(1)根本控制不了前端的请求频率——前端会一次性加载所有图层,瞬间把请求发出去,自然触发了速率限制。
下面给你几个可行的解决思路和修改后的代码:
1. 改用Python直接调用API获取路线,再用Polyline图层绘制
这样能完全在Python端控制请求间隔,避开前端的批量请求问题。步骤如下:
- 用
requests库直接调用Directions API,获取路线的坐标点 - 将坐标点转为gmaps的Polyline图层添加到地图
- 在Python端严格控制请求间隔,确保符合API的速率配额
修改后的代码示例:
import gmaps import time import pandas as pd import requests dict_k ={} dict_k['st_coordinates'] =[ '24.760669, 54.704782','25.168596, 56.355549','25.004274, 55.063742','25.000252, 55.060932', '24.872900, 55.137325','24.537609, 54.383664','24.050339, 53.470903','24.211435, 55.424501', '24.196804, 55.855923','24.308309, 54.675861','24.988239, 55.104435','24.985047, 55.071542', '24.306433, 54.490205','25.000252, 55.060932','24.536064, 54.383048' ] dict_k['en_coordinates'] =[ '24.454036, 54.376656','24.130453, 55.801786','23.931339, 53.045892','24.171,54.408', '24.454036, 54.376656','24.130453, 55.801786','23.931339, 53.045892','24.171,54.408', '24.454036, 54.376656','24.130453, 55.801786','23.931339, 53.045892','24.171,54.408', '24.454036, 54.376656','24.130453, 55.801786','23.931339, 53.045892'] key = 'AIzA...............' dataframe = pd.DataFrame.from_dict(dict_k) def draw_map(dataframe, key): gmaps.configure(key) fig = gmaps.figure() directions_api_url = "https://maps.googleapis.com/maps/api/directions/json" for i in range(len(dataframe)): # 安全解析坐标,替换eval start_coords = tuple(map(float, dataframe['st_coordinates'].iloc[i].split(', '))) end_coords = tuple(map(float, dataframe['en_coordinates'].iloc[i].split(', '))) # 调用Directions API获取路线 params = { 'origin': f"{start_coords[0]},{start_coords[1]}", 'destination': f"{end_coords[0]},{end_coords[1]}", 'key': key } response = requests.get(directions_api_url, params=params) route_data = response.json() if route_data['status'] == 'OK': # 提取路线的坐标点 polyline_points = route_data['routes'][0]['overview_polyline']['points'] # 解码polyline(需要安装polyline库:pip install polyline) import polyline route_coords = polyline.decode(polyline_points) # 添加Polyline图层 fig.add_layer(gmaps.Polyline( path=route_coords, stroke_color='blue', stroke_opacity=0.8, stroke_weight=3 )) else: print(f"请求{i+1}失败,状态:{route_data['status']}") # 控制请求间隔,每秒不超过10次(免费版配额),这里设为0.11秒确保不超限 if i > 0: time.sleep(0.11) return fig df = draw_map(dataframe, key) df
2. 检查API密钥的配额设置
即使你有免费额度,也要去Google Cloud Console确认:
- Directions API的每秒请求数(QPS)配额是否被手动调低(默认免费版是10 QPS)
- 确保API密钥没有被限制只能从特定IP或域名访问(如果是本地Jupyter,要允许所有来源,或者添加你的IP)
3. 关于批处理的补充
如果还是想用directions_layer,那只能通过分批渲染地图的方式——比如先渲染前10条路线,显示后,再手动运行代码渲染下一批,但这种方式体验不好,不如第一种方案可控。
另外,注意你的代码里用eval解析坐标是不安全的,建议用split+map(float)的方式替换,避免潜在的代码注入风险。
内容的提问来源于stack exchange,提问作者Wael
相关产品推荐
相关产品推荐

