Google 地图自动完成 - 最多 3 个字符类型

Google map autocomplete - maximum 3 character type

我已经实现了 Google 带有搜索框的地图,它允许用户通过搜索来 select 地址。

在该搜索框中,即使我输入 1 个字符,它也会搜索。我希望用户至少输入 3 个字符,否则它不应进行搜索。

My JS Fiddle is: http://jsfiddle.net/upsidown/2NhsE/

我该怎么做? Google 是否提供该限制?

检查 pac-input 文本框中输入的文本长度。如果长度大于 3,则将该查询转发给 google 地图。

Google 目前不为位置自动完成元素提供此选项。

public 问题跟踪器中有一个功能请求。看看 issue 5831。该问题的状态为已接受,但是没有任何 ETA 暴露。您可以为这个问题加注星标以添加您的投票并接收进一步的更新。

还有一个 comment #15 建议如何使用自动完成服务实现此功能。


更新:2018 年 6 月 4 日

此功能被标记为不会修复(已过时)

This feature request is obsoleted by the new session-based billing for Places autocomplete. Please refer to the "Place Autocomplete" section of https://cloud.google.com/maps-platform/user-guide/pricing-changes/ for more details.

您可以像这样验证字符串并重建自动完成

在这种情况下我使用 jQuery 这个 API stopImmediatePropagation 也关于 val

input.keyup(function(e){
if(input.val().length<2){
    e.stopImmediatePropagation()
}
else{
   createAutoComplete(input)
} 

您可以在用户至少输入最少的字符后初始化自动完成。下面的代码监听输入 jQuery 的按键事件。当用户键入第三个字符时,它将初始化自动完成。

我认为您的意图是避免额外的 API 请求。这应该有效。

window.autocompleteobj =false;

//initialize map after 2 chars are typed
$('#autocompleteinput').keyup(function(e) {
    if ($('#autocompleteinput').val().length < 3) {
        e.stopImmediatePropagation()
    } else {
        if (window.autocompleteobj == false) {
            window.autocompleteobj = new google.maps.places.Autocomplete(autocompleteinput);
            google.maps.event.addListener(autocompleteobj, 'place_changed', function() {
               //your stuff here
            });
        }
    }
});