使用Python与VSCode调用Google Maps API仅返回1条结果的排查请求
问题:Google Maps Places Nearby API 返回结果异常,不符合商家搜索需求
问题现象
- 初始用关键词搜索时,返回大量非目标类型的结果
- 删除关键词改用
opennow=True后,仅返回1条结果(为搜索坐标所在的城镇,而非商家)
代码问题分析
搜索半径过小:
代码中distance = (1),Places Nearby API的radius参数单位是米,1米的范围仅能覆盖坐标点本身,因此返回城镇地点是合理的,根本无法覆盖周边商家。请求参数不一致:
第一次调用places_nearby未添加opennow=True,后续循环请求却加入了该参数,导致前后搜索条件不一致,可能出现结果断层或不符合预期的情况。缺少商家类型过滤:
未指定type参数时,API会返回所有类型的地点(包括城镇、地标、住宅等),而非仅商家。需要通过type参数限定目标商家类型。
修正后的代码
import googlemaps import time import pandas as pd map_client = googlemaps.Client(API_KEY) # 调整搜索半径为5公里(可根据需求修改,单位:米) location = (54.970121, -2.101585) radius = 5000 business_list = [] # 统一设置过滤条件:仅返回当前营业的餐厅(可替换为目标类型,如store/cafe等) response = map_client.places_nearby( location=location, radius=radius, opennow=True, type='restaurant' ) business_list.extend(response.get('results')) next_page_token = response.get('next_page_token') while next_page_token: time.sleep(2) # API要求分页请求间隔至少2秒 response = map_client.places_nearby( location=location, radius=radius, opennow=True, type='restaurant', # 与首次请求参数保持一致 page_token=next_page_token ) business_list.extend(response.get('results')) next_page_token = response.get('next_page_token') df = pd.DataFrame(business_list) df['url'] = 'https://www.google.com/maps/place/?q=place_id:' + df['place_id'] df.to_excel('Toby Business.xlsx', index=False)
补充说明
type参数选择:需根据需求指定对应商家类型,比如store(商店)、cafe(咖啡馆)、gas_station(加油站)等,确保仅返回目标类型的商家。- 半径调整:根据要覆盖的区域大小修改
radius值,单位为米,例如1000代表1公里范围。 - 分页间隔:
time.sleep(2)不可省略,否则可能触发API请求限制导致失败。
内容的提问来源于stack exchange,提问作者I_March1127
相关产品推荐
相关产品推荐

