我使用谷歌自动完成地方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&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>
我一直在玩谷歌自动补全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
}
}
}
如果您查看返回的结果对象,您将看到有一个address_components数组,它将包含表示地址的不同部分的几个对象。在这些对象中,它将包含一个'types'数组,在这个'types'数组中,您将看到与地址相关的不同标签,包括一个国家。
<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);
其他类型的参考:http://code.google.com/apis/maps/documentation/places/supported_types.html#table2