输入 3 个字符后自动完成 Google-place-API



我正在使用 React.JS在搜索框中输入 3 个字符后,我需要调用 google-place-api 自动完成功能。他们在文档中有偏移量,但它不起作用。 这是我的代码:

renderAutoComplete() {
let attr = this;
const { google, map } = this.props;
var autocompleParam = {
offset: 4
}
const aref = this.refs.autocomplete;
const node = ReactDOM.findDOMNode(aref);
var start_location = document.getElementById('start_location')
var from_address = new google.maps.places.Autocomplete(
start_location, autocompleParam, {
});
from_address.setComponentRestrictions({ 'country': ['uk'] });
google.maps.event.addListener(from_address, 'place_changed', function (e) {
document.getElementById('start_location').style.borderColor = '';
var place = from_address.getPlace();
attr.props.onChangeLocationSearch(place.place_id);
attr.props.onGetLocationInfo(e);
});
var to_address = new google.maps.places.Autocomplete(
(document.getElementById('end_location')), {
});
to_address.setComponentRestrictions({ 'country': ['uk'] });
google.maps.event.addListener(to_address, 'place_changed', function (e) {
var place = to_address.getPlace();
document.getElementById('end_location').style.borderColor = '';
attr.props.onChangeEndLocationSearch(place.place_id);
attr.props.onReturnLocation(e);
});
}

您可以尝试获取"to_address"值的长度,然后允许进行 .getPlace(( 调用。像这样:

var autocompleParam = {
offset: 3
}    
google.maps.event.addListener(to_address, 'place_changed', function (e) {
if (to_address.value.length < autocompleParam.offset) {
return;
}
var place = to_address.getPlace();
document.getElementById('end_location').style.borderColor = '';
attr.props.onChangeEndLocationSearch(place.place_id);
attr.props.onReturnLocation(e);
});

相关内容

  • 没有找到相关文章

最新更新