Google Maps Geolocator API区域地址获取代码故障求助
解决Google Maps API获取指定区域地址无输出问题
原代码存在的核心问题
- API接口误用:你用的Geocoding API的
bounds参数仅用于约束反向地理编码的结果范围,无法直接获取区域内的所有地址。要实现需求,需使用Places API的Nearby Search接口。 - 无效区域边界:你定义的
lat1/lng1与lat2/lng2完全重复,lat3/lng3与lat4/lng4也重复,无法构成有效区域。API的区域边界只需传入西南、东北两个对角坐标即可。 - API密钥格式错误:你提供的密钥不符合Google Maps API密钥规范,需在Google Cloud控制台生成有效密钥,并确保启用了对应API(Places API)。
- Colab文件路径错误:Colab无法直接访问本地Windows路径
C:/Users/...,需挂载Google Drive或上传文件到Colab临时存储。 - 未执行核心逻辑:代码仅定义了函数,但未调用
get_addresses_in_region和save_addresses_to_excel,导致没有实际执行请求与保存操作。
修复后的代码
以下是适配需求的完整代码,使用Places API获取指定区域地址,并处理Colab文件存储问题:
import requests import pandas as pd from google.colab import drive # 挂载Google Drive(用于持久化保存文件) drive.mount('/content/drive') # 替换为你的有效Google Maps API密钥(需启用Places API和Geocoding API) api_key = "你的有效API密钥" # 定义区域的西南、东北对角坐标(基于你提供的有效点位) southwest_lat = 38.1540804 southwest_lng = 23.9595323 northeast_lat = 38.1579862 northeast_lng = 23.9626608 # 保存路径(可选Colab临时路径或Drive路径) file_path = "/content/drive/MyDrive/addresses.xlsx" # 临时路径可写为"/content/addresses.xlsx" def get_addresses_in_region(api_key, sw_lat, sw_lng, ne_lat, ne_lng): addresses = [] # Places API Nearby Search接口配置 base_url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json" params = { "key": api_key, "location": f"{(sw_lat + ne_lat)/2},{(sw_lng + ne_lng)/2}", # 区域中心点 "radius": 500, # 搜索半径(根据区域大小调整) "bounds": f"{sw_lat},{sw_lng}|{ne_lat},{ne_lng}", # 限制搜索范围 "type": "address" } while True: response = requests.get(base_url, params=params) if response.status_code != 200: print(f"请求失败:{response.json().get('error_message', '未知错误')}") break data = response.json() # 通过place_id调用Geocoding API获取格式化地址 for place in data["results"]: place_id = place["place_id"] geocode_url = f"https://maps.googleapis.com/maps/api/geocode/json?place_id={place_id}&key={api_key}" geocode_res = requests.get(geocode_url) if geocode_res.status_code == 200 and geocode_res.json()["results"]: addresses.append(geocode_res.json()["results"][0]["formatted_address"]) # 处理分页结果 if "next_page_token" not in data: break params["pagetoken"] = data["next_page_token"] return addresses def save_addresses_to_excel(addresses, file_path): df = pd.DataFrame({"Address": addresses}) df.to_excel(file_path, index=False) print(f"地址已保存至:{file_path}") # 执行核心逻辑 if __name__ == "__main__": addresses = get_addresses_in_region(api_key, southwest_lat, southwest_lng, northeast_lat, northeast_lng) if addresses: save_addresses_to_excel(addresses, file_path) else: print("未获取到任何地址")
额外注意事项
- 需在Google Cloud控制台启用Places API和Geocoding API,并为密钥设置合理的配额与权限。
- 若区域较大,可调整
radius参数或通过分页机制获取更多结果。 - Colab临时路径下的文件会在会话结束后删除,建议挂载Google Drive实现持久化存储。
内容的提问来源于stack exchange,提问作者Georgios Bekas
相关产品推荐
相关产品推荐

