我目前只能限制一个国家的地点,但我也想限制在一个特定的城市。有什么办法可以做到这一点吗?这是我当前的代码:
var autocomplete,
options = {
types: ['geocode'],
componentRestrictions: {country: 'est'}
};
autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace().formatted_address;
$(input).attr('value',place);
});
发布于 2017-01-16 21:00:11
正如Luke所说,places自动完成功能允许您使用componentRestrictions仅按国家进行过滤。
但是您可以对搜索请求字符串使用一个小技巧。只需在请求中添加带有城市名称的前缀。
var prefix = 'Kyiv, ';
$(input).on('input',function(){
var str = input.value;
if(str.indexOf(prefix) == 0) {
// string already started with prefix
return;
} else {
if (prefix.indexOf(str) >= 0) {
// string is part of prefix
input.value = prefix;
} else {
input.value = prefix+str;
}
}
});
发布于 2015-10-20 11:58:34
Places Autocomplete目前允许您使用componentRestrictions按国家/地区过滤。在您的情况下,我要做的是使用options参数根据定义相关城市的边界进行过滤:
var cityBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(25.341233, 68.289986),
new google.maps.LatLng(25.450715, 68.428345));
var options = {
bounds: cityBounds,
types: ['geocode'],
componentRestrictions: {country: 'est'}
};
发布于 2017-04-07 05:08:13
谷歌提供了两种方法来实现这一点。如果你不满意,因为在像印度这样的国家,它运行得不好,因为这里的州和条款没有矩形或结构边界。
1.LatLngBound (LatLng西南,LatLng东北):,您可以在其中提供纬度和经度以形成一个矩形。
2. Location (Lat,Lng) & Radius:,您可以在其中提供纬度和经度以形成一个圆。
但是这些方法的问题是,如果你来自像印度这样的国家,它们不能提供预期的结果,这些国家和条款不像美国那样是结构化的形状(矩形)。
如果你正面临着同样的问题,那就有一个黑客。使用jQuery/Jacascript,您可以附加一些函数,这些函数将在与Places API的Autocomplete对象绑定的文本输入中一致地保持城市名称。
这就是它:
<script>
$(document).ready(function(){
$("#locality").val(your-city-name) //your-city-name will have city name and some space to seperate it from actual user-input for example: “Bengaluru | ”
});
$("#locality").keydown(function(event) { //locality is text-input box whixh i supplied while creating Autocomplete object
var localeKeyword = “your-city-name”
var localeKeywordLen = localeKeyword.length;
var keyword = $("#locality").val();
var keywordLen = keyword.length;
if(keywordLen == localeKeywordLen) {
var e = event || window.event;
var key = e.keyCode || e.which;
if(key == Number(46) || key == Number(8) || key == Number(37)){
e.preventDefault();
}//Here I am restricting user to delete city name (Restricting use of delete/backspace/left arrow) if length == city-name provided
if(keyword != localeKeyword) {
$("#locality").val(localeKeyword);
}//If input-text does not contain city-name put it there
}
if(!(keyword.includes(localeKeyword))) {
$("#locality").val(localeKeyword);
}//If keyword not includes city name put it there
});
https://stackoverflow.com/questions/33214788
复制相似问题