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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8282026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:25:32  来源:igfitidea点击:

How to limit google autocomplete results to City and Country only

javascriptautocompletegoogle-maps-api-3

提问by JohnTaa

I am using google autocomplete places javascript to return suggested results for my searchbox , what I need is to only show the city and the country related to the characters entered but google api will give a lot of general places results which I dont need , so how to limit the result to show only city and the country .

我正在使用谷歌自动完成地方 javascript 为我的搜索框返回建议的结果,我需要的是只显示与输入的字符相关的城市和国家,但谷歌 api 会给出很多我不需要的一般地点结果,那么如何将结果限制为仅显示城市和国家。

I am using the following Example:

我正在使用以下示例:

<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>

回答by Francois

You can try the country restriction

你可以试试国家限制

function initialize() {

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

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

More info:

更多信息:

ISO 3166-1 alpha-2can 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.

ISO 3166-1 alpha-2可用于将结果限制为特定组。目前,您可以使用 componentRestrictions 按国家/地区过滤。

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



Officially assigned country codes官方指定的国家代码

回答by UnLoCo

<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="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"></script>
<script type="text/javascript">
   function initialize() {
      var input = document.getElementById('searchTextField');
      var options = {
        types: ['geocode'] //this should work !
      };
      var autocomplete = new google.maps.places.Autocomplete(input, options);
   }
   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>

var options = {
  types: ['geocode'] //this should work !
};
var autocomplete = new google.maps.places.Autocomplete(input, options);

reference to other types: http://code.google.com/apis/maps/documentation/places/supported_types.html#table2

对其他类型的引用:http: //code.google.com/apis/maps/documentation/places/supported_types.html#table2

回答by Ravindra

try this

尝试这个

<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="https://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places&region=in" 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>

http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"

http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"

Change this to: "region=in" (in=india)

将其更改为:“region=in”(in=india)

"http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&region=in" type="text/javascript"

" http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places®ion=in" type="text/javascript"

回答by Kiran Muralee

The answergiven by Francois results in listing all the cities from a country. But if the requirement is to list all the regions (cities + states + other regions etc) in a country or the establishments in the country, you can filter results accordingly by changing types.

弗朗索瓦给出的答案会列出一个国家的所有城市。但是,如果要求列出一个国家/地区的所有地区(城市 + 州 + 其他地区等)或该国家/地区的机构,您可以通过更改类型来相应地过滤结果。

List only cities in the country

仅列出该国的城市

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

List all cities, states and regions in the country

列出全国所有城市、州和地区

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

List all establishments — such as restaurants, stores, and offices in the country

列出所有机构——例如该国的餐馆、商店和办公室

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

More information and options available at

更多信息和选项,请访问

https://developers.google.com/maps/documentation/javascript/places-autocomplete

https://developers.google.com/maps/documentation/javascript/places-autocomplete

Hope this might be useful to someone

希望这可能对某人有用

回答by seBaka28

Basically same as the accepted answer, but updated with new type and multiple country restrictions:

与接受的答案基本相同,但更新了新类型和多个国家/地区限制:

function initialize() {

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

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

Using '(regions)'instead of '(cities)'allows to search by postal code as well as city name.

使用'(regions)'代替'(cities)'允许按邮政编码和城市名称搜索。

See official documentation, Table 3: https://developers.google.com/places/supported_types

参见官方文档,表 3:https: //developers.google.com/places/supported_types

回答by wmock

I've been playing around with the Google Autocomplete API for a bit and here's the best solution I could find for limiting your results to only countries:

我一直在玩 Google Autocomplete API,这是我能找到的将结果仅限于国家/地区的最佳解决方案:

var autocomplete = new google.maps.places.Autocomplete(input, options);
var result = autocomplete.getPlace();
console.log(result); // take a look at this result object
console.log(result.address_components); // a result has multiple address components

for(var i = 0; i < result.address_components.length; i += 1) {
  var addressObj = result.address_components[i];
  for(var j = 0; j < addressObj.types.length; j += 1) {
    if (addressObj.types[j] === 'country') {
      console.log(addressObj.types[j]); // confirm that this is 'country'
      console.log(addressObj.long_name); // confirm that this is the country name
    }
  }
}

If you look at the result object that's returned, you'll see that there's an address_components array which will contain several objects representing different parts of an address. Within each of these objects, it will contain a 'types' array and within this 'types' array, you'll see the different labels associated with an address, including one for country.

如果您查看返回的结果对象,您会看到有一个 address_components 数组,该数组将包含表示地址不同部分的多个对象。在这些对象中的每一个中,它将包含一个“types”数组,在这个“types”数组中,您将看到与地址关联的不同标签,包括国家/地区的标签。

回答by Kir Mazur

Also you will need to zoom and center the map due to your country restrictions!

此外,由于您所在的国家/地区的限制,您还需要缩放地图并使其居中!

Just use zoom and center parameters! ;)

只需使用缩放和中心参数!;)

function initialize() {
  var myOptions = {
    zoom: countries['us'].zoom,
    center: countries['us'].center,
    mapTypeControl: false,
    panControl: false,
    zoomControl: false,
    streetViewControl: false
  };

  ... all other code ...

}

回答by Cenk YAGMUR

I found a solution for myself

我为自己找到了解决方案

var acService = new google.maps.places.AutocompleteService();
var autocompleteItems = [];

acService.getPlacePredictions({
    types: ['(regions)']
}, function(predictions) {
    predictions.forEach(function(prediction) {
        if (prediction.types.some(function(x) {
                return x === "country" || x === "administrative_area1" || x === "locality";
            })) {
            if (prediction.terms.length < 3) {
                autocompleteItems.push(prediction);
            }
        }
    });
});

this solution only show city and country..

此解决方案仅显示城市和国家/地区..

回答by Hina Vaja

<html>
  <head>
    <title>Example Using Google Complete API</title>   
  </head>
  <body>

<form>
   <input id="geocomplete" type="text" placeholder="Type an address/location"/>
    </form>
   <script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places"></script>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

  <script src="http://ubilabs.github.io/geocomplete/jquery.geocomplete.js"></script>
  <script>
   $(function(){        
    $("#geocomplete").geocomplete();                           
   });
  </script>
 </body>
</html>

For more information visit this link

有关更多信息,请访问此链接