我正在使用google autocomplete places javascript为我的搜索框返回建议结果,我需要的是只显示与输入字符相关的城市和国家,但google api将提供许多我不需要的一般地点结果,因此如何限制结果仅显示城市和国家.

我使用以下示例:

<html>
<head>
<style type="text/css">
   body {
         font-family: sans-serif;
         font-size: 14px;
   }
</style>

<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places" type="text/javascript"></script>
<script type="text/javascript">
   function initialize() {
      var input = document.getElementById('searchTextField');
      var autocomplete = new google.maps.places.Autocomplete(input);
   }
   google.maps.event.addDomListener(window, 'load', initialize);
</script>

</head>
<body>
   <div>
      <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">
   </div>
</body>
</html>

推荐答案

你可以试试乡村限制

function initialize() {

 var options = {
  types: ['(cities)'],
  componentRestrictions: {country: "us"}
 };

 var input = document.getElementById('searchTextField');
 var autocomplete = new google.maps.places.Autocomplete(input, options);
}

更多信息:

ISO 3166-1 alpha-2 can be used to restrict results to specific groups. Currently, you can use componentRestrictions to filter by country.

The country must be passed as as a two character, ISO 3166-1 Alpha-2 compatible country code.


Officially assigned country codes

Javascript相关问答推荐

Express.js:以块形式发送响应

获取最接近的父项(即自定义元素)

如何提取Cypress中文本

如何将Cookie从服务器发送到用户浏览器

我正在建立一个基于文本的游戏在react ,我是从JS转换.我怎样才能使变量变呢?

如何在ASP.NET JavaScript中使用Google Charts API仅对绘制为负方向的条形图移动堆叠条形图标签位置

如何从HTML对话框中检索单选项组的值?

material UI按钮组样式props 不反射

如何创建返回不带`new`关键字的实例的类

如何在 Select 文本时停止Click事件?

当我try 将值更改为True时,按钮不会锁定

JS Animate()方法未按预期工作

警告框不显示包含HTML输入字段的总和

如何使用Astro优化大图像?

通过跳过某些元素的对象进行映射

Socket.IO在刷新页面时执行函数两次

Pevent触发material 用户界面数据网格中的自动保存

Promise.race()返回已解析的promise ,而不是第一个被拒绝的promise

在Puppeteer中使用promise进行日志(log)记录时出现TargetCloseError

使用Perl Selify::Remote::Driver执行Java脚本时出错