Warm tip: This article is reproduced from serverfault.com, please click

javascript-如何将谷歌自动完成结果仅限于城市和国家

(javascript - How to limit google autocomplete results to City and Country only)

发布于 2011-11-26 22:12:44

我正在使用谷歌自动完成地方 javascript 为我的搜索框返回建议的结果,我需要的是只显示与输入的字符相关的城市和国家,但谷歌 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>
Questioner
JohnTaa
Viewed
11
8,358 2014-07-14 15:47:38

你可以试试国家限制

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可用于将结果限制为特定组。目前,你可以使用 componentRestrictions 按国家/地区过滤。

国家/地区必须作为两个字符传递,与 ISO 3166-1 Alpha-2 兼容的国家/地区代码。


官方指定的国家代码