首页 > 解决方案 > 为什么 Google Maps API 上的组件过滤不起作用?

问题描述

我在使用 Google Maps Geocoding API 时遇到问题。

特别是,我无法使用“国家/地区”进行组件过滤。

我已经定义了一个 api 调用函数,如下所示:

def extract_lat_lng(address_or_postalcode, country_code, data_type = 'json'):
    api_key = "your-api-key-here"
    endpoint = f"https://maps.googleapis.com/maps/api/geocode/{data_type}"
    country = f"country:{country_code}"
    params = {"address": address_or_postalcode, "key": api_key, "components=": country}
    url_params = urlencode(params)
    url = f"{endpoint}?{url_params}"
    r = requests.get(url)
    if r.status_code not in range(200, 299): 
        return {}
    latlng = {}
    try:
        latlng = r.json()['results'][0]['geometry']['location']
    except:
        pass
    return latlng.get("lat"), latlng.get("lng")

我试着打电话:

extract_lat_lng('Santiago, EM','MX')

我得到了结果:

Out[74]: (-33.4488897, -70.6692655)

这些是智利圣地亚哥的地理坐标。我想要墨西哥圣地亚哥的地理坐标(州 = EM)。

有没有办法让这个工作?

标签: apigoogle-maps

解决方案


解决方案是从参数变量中删除“=”,如下所示:

params = {"address": address_or_postalcode, "key": api_key, "components": country}

推荐阅读