使用Google Maps Geocoding API传入place_id参数时触发错误
Google Maps Geocoding API传入place_id参数时触发错误
看起来你踩了Python版googlemaps库的一个小坑——geocode()方法本身并不支持直接传入place_id这个关键字参数,这就是你看到报错的原因。
虽然Google Maps Geocoding API的REST接口确实支持place_id参数,但Python客户端库的geocode()方法把这个参数包装到了components参数里,而不是让它作为独立参数传入。
你可以把place_id放到components字典里,这样调用就没问题了:
import googlemaps from secret_key import key gmaps = googlemaps.Client(key=key) # 用components参数传入place_id geocode_result = gmaps.geocode(components={'place_id': 'ChIJgUbEo8cfqokR5lP9_Wh_DaM'})
执行这段代码后,你就能拿到对应place_id的经纬度信息了。如果需要提取经纬度,可以从返回结果的geometry.location字段获取,比如:
if geocode_result: lat = geocode_result[0]['geometry']['location']['lat'] lng = geocode_result[0]['geometry']['location']['lng'] print(f"纬度: {lat}, 经度: {lng}")
备注:内容来源于stack exchange,提问作者Michael Diam




