You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Google Places自动补全设置特定国家的componentRestrictions限制

如何用componentRestrictions限制Google自动补全的国家范围

嘿,这事儿其实挺容易搞定的!你只需要在请求的qs参数里添加componentRestrictions配置项,就能把自动补全结果限定在特定国家了。

具体操作细节:

  • componentRestrictions是一个配置对象,其中的country字段用来指定目标国家,支持两种设置方式:
    • 单个国家:直接传入两位ISO 3166-1 Alpha-2格式的国家代码(比如中国是'cn',美国是'us')
    • 多个国家:传入包含多个国家代码的数组(比如['us', 'ca']表示仅返回美国和加拿大的结果)

修改后的完整代码示例:

假设你想把结果限定在中国,代码可以改成这样:

var headers = { 
  'User-Agent': 'Super Agent/0.0.1', 
  'Content-Type': 'application/x-www-form-urlencoded' 
};

// 配置请求参数
var options = { 
  url: "https://maps.googleapis.com/maps/api/place/autocomplete/json", 
  method: 'POST', 
  headers: headers, 
  qs: { 
    key: gkey, 
    input: input, 
    types: ['(cities)'],
    // 添加国家限制配置
    componentRestrictions: { 
      country: 'cn' 
    }
  }
};

如果需要同时限制多个国家,只需要把country的值改成数组即可:

componentRestrictions: { 
  country: ['us', 'ca'] 
}

这样设置后,Google返回的自动补全结果就只会关联你指定的国家啦!

内容的提问来源于stack exchange,提问作者Raz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:47:39