如何将 Google 地方自动完成功能配置为仅在输入字段中至少有 n 个字母时执行请求

How to configure Google Places Autocomplete only to do requests if there are at least n letters in the input field?

本文关键字:字段 执行 请求 输入 方自动 Google 成功 配置 功能      更新时间:2023-09-26

My Code:

var input = /** @type {!HTMLInputElement} */(
            document.getElementById('place'));              
var options = {               
        types: ['(regions)'],
        componentRestrictions: {country: "de"},
        offset: 3
    };  
function initialize() {             
    var autocomplete = new google.maps.places.Autocomplete(input, options);
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
       //some stuff here
    });
}

google.maps.event.addDomListener(window, 'load', initialize);

来自谷歌的文字:

可选参数

offset — 输入项中>服务用于匹配预测的最后一个字符的位置。例如,如果输入 是"谷歌",偏移量是 3,服务将在"Goo"上匹配。这 由偏移量确定的字符串与 中的第一个单词匹配 仅输入项。例如,如果输入词是"Google abc" 并且偏移量为 3,服务将尝试与 'Goo 匹配 美国广播公司'。如果未提供偏移量,则服务将使用整个术语。 偏移量通常应设置为文本插入符号的位置。

那么为什么偏移选项不起作用呢?我已经在第一封信之后收到了建议。但我想减少要求。

您可以使用 jquery onchange 事件侦听器,例如:

$('#yourinput').on('change', function(e){
    var n = 3
    if($(this).value().length() < n){
        return
    }else{
        //do your autocomplete
    }

其中var n是要用作地理编码开始的字符数。