代码之家  ›  专栏  ›  技术社区  ›  designosis

首次使用后如何触发google places自动完成结果下拉列表?

  •  1
  • designosis  · 技术社区  · 7 年前

    使用 谷歌地图javascript api (通过 <script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places&callback=initAutocomplete" async defer></script> ),我的地址输入…

    enter image description here

    …当我键入“1251”时显示自动完成信息…

    enter image description here

    …并在单击地址(或按回车键)时将完整地址添加到输入:

    enter image description here

    目前,如果我再次单击地址输入(在添加地址之后),它只是将焦点添加到输入,而没有其他内容:

    enter image description here

    我的问题是: 单击已自动完成的输入时,如何使用输入的数据再次触发下拉列表?

    点击删除一次(只需更改结尾 USA US )重新打开下拉列表,但我不希望用户必须更改条目才能看到下拉列表。我试过的是:

    $('.geoloc input').on({
    
        // neither 'place_changed' nor 'focus' trigger the dropdown (doesn't work)
        click: function(){
            google.maps.event.trigger(this, 'place_changed');
            // or
            google.maps.event.trigger(this, 'focus', {});
        },
    
        // enter selects first address from dropdown (works)
        keydown: function(e){
            if (e.keyCode == 13) {
                google.maps.event.trigger(this, 'keydown', {keyCode:40});
                google.maps.event.trigger(this, 'keydown', {keyCode:13});
                this.blur();
            }
        }
    });
    

    使用字段值以编程方式触发下拉列表的正确方法是什么?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Joseph Marikle    7 年前

    我想我知道你想完成什么。您希望保留文本字段的状态,以便在重新获得焦点时,它可以恢复到原来的位置。你想要这个吗?

    var input = document.getElementById('searchTextField');
    var autocomplete = new google.maps.places.Autocomplete(input);
    
    input.addEventListener('input', function () {
      this.dataset.originalVal = this.value;
    });
    input.addEventListener('focus', function () {
      this.value = input.dataset.originalVal ? input.dataset.originalVal : this.value;
    });
    input {
      width: 300px;
    }
    <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
    <input id="searchTextField" type="text">