【问题标题】:google-place-api autocomplete after typing 3 characters输入 3 个字符后 google-place-api 自动完成
【发布时间】:2019-03-15 10:43:54
【问题描述】:

我正在使用 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);
    });
}

【问题讨论】:

标签: reactjs google-maps autocomplete google-places-api


【解决方案1】:

您可以尝试获取 '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);
});

【讨论】:

  • 感谢您的回答。我试过这个,这不起作用。我担心的是减少 google place 自动完成 api 调用以输入每个字符
猜你喜欢
  • 2015-07-28
  • 2016-10-28
  • 2015-02-20
  • 2016-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多