Google商家信息自动填充功能 - 在输入密钥上选择第一个结果?

时间:2013-01-30 10:23:46

标签: javascript google-maps google-maps-api-3 google-places-api google-places

我正在使用Google地方自动填充功能,我只是希望它在表单字段中按下回车键并且存在建议时选择结果列表中的顶部项目。我知道之前有人问过:

Google maps Places API V3 autocomplete - select first option on enter

Google maps Places API V3 autocomplete - select first option on enter (and have it stay that way)

但这些问题的答案似乎并没有真正起作用,或者它们解决了特定的附加功能。

似乎以下内容应该有效(但事实并非如此):

$("input#autocomplete").keydown(function(e) {
  if (e.which == 13) {          
    //if there are suggestions...
    if ($(".pac-container .pac-item").length) {
      //click on the first item in the list or simulate a down arrow key event
      //it does get this far, but I can't find a way to actually select the item
      $(".pac-container .pac-item:first").click();
    } else {
      //there are no suggestions
    }
  }
});

任何建议都将不胜感激!

9 个答案:

答案 0 :(得分:11)

我已经阅读了这个问题的许多答案以及相关问题'答案很多次,才发现最好的答案是this one(Nota:遗憾的是,它不是公认的答案!)。

我修改了2或3行,将其转换为可在代码中复制/粘贴的即用型功能,并应用于许多input个元素如果需要的话。这是:

var selectFirstOnEnter = function(input){      // store the original event binding function
    var _addEventListener = (input.addEventListener) ? input.addEventListener : input.attachEvent;
    function addEventListenerWrapper(type, listener) { // Simulate a 'down arrow' keypress on hitting 'return' when no pac suggestion is selected, and then trigger the original listener.
    if (type == "keydown") { 
      var orig_listener = listener;
      listener = function (event) {
      var suggestion_selected = $(".pac-item-selected").length > 0;
        if (event.which == 13 && !suggestion_selected) { var simulated_downarrow = $.Event("keydown", {keyCode:40, which:40}); orig_listener.apply(input, [simulated_downarrow]); }
        orig_listener.apply(input, [event]);
      };
    }
    _addEventListener.apply(input, [type, listener]); // add the modified listener
  }
  if (input.addEventListener) { input.addEventListener = addEventListenerWrapper; } else if (input.attachEvent) { input.attachEvent = addEventListenerWrapper; }
}

用法:

selectFirstOnEnter(input1);
selectFirstOnEnter(input2);
...

答案 1 :(得分:9)

我正在重新发布Google maps Places API V3 autocomplete - select first option on enter的答案:

似乎有一个更好,更干净的解决方案:使用google.maps.places.SearchBox代替google.maps.places.Autocomplete。 代码几乎相同,只是从多个地方获得第一个。按Enter键返回正确的列表 - 因此它开箱即用,不需要黑客攻击。

请参阅示例HTML页面:

http://rawgithub.com/klokan/8408394/raw/5ab795fb36c67ad73c215269f61c7648633ae53e/places-enter-first-item.html

相关的代码段是:

var searchBox = new google.maps.places.SearchBox(document.getElementById('searchinput'));

google.maps.event.addListener(searchBox, 'places_changed', function() {
  var place = searchBox.getPlaces()[0];

  if (!place.geometry) return;

  if (place.geometry.viewport) {
    map.fitBounds(place.geometry.viewport);
  } else {
    map.setCenter(place.geometry.location);
    map.setZoom(16);
  }
});

示例的完整源代码位于:https://gist.github.com/klokan/8408394

答案 2 :(得分:4)

在我的网站中实现相同的功能我需要jQuery模拟插件(https://github.com/jquery/jquery-simulate)然后附加事件:

$("input#autocomplete").focusin(function () {
    $(document).keypress(function (e) {
        if (e.which == 13) {
            $("input#autocomplete").trigger('focus');
            $("input#autocomplete").simulate('keydown', { keyCode: $.ui.keyCode.DOWN } ).simulate('keydown', { keyCode: $.ui.keyCode.ENTER });
        }
    });
});

该插件将模拟按下DOWN键然后按ENTER键的操作,ENTER本身不起作用,我找不到另一种方法来选择第一个选项。

希望这有帮助

答案 3 :(得分:4)

工作解决方案,用于监听用户是否已开始使用键盘向下导航列表,而不是每次都触发错误导航

https://codepen.io/callam/pen/RgzxZB

以下是重点:

{{1}}

答案 4 :(得分:2)

这就是我所做的并且有效:

<强> HTML:

<input name="location" id="autocomplete" autocomplete="off" type="text" class="textbx" placeholder="Enter Destination" required>

<强> googleautocompletecustomized.js:

        function initialize() {
      // Create the autocomplete object, restricting the search
      // to geographical location types.
      if($('#autocomplete').length){
          autocomplete = new google.maps.places.Autocomplete(
              (document.getElementById('autocomplete')),
              {
                types: ['(regions)'],
                componentRestrictions: {country: "in"}
              });
          google.maps.event.addListener(autocomplete, 'place_changed', function() {
            $('#autocomplete').closest('form').data('changed', true);
            fillInAddress();
          });         
      }

    //select first result
        $('#autocomplete').keydown(function (e) {
            if (e.keyCode == 13 || e.keyCode == 9) {
                $(e.target).blur();
                if($(".pac-container .pac-item:first span:eq(3)").text() == "")
                    var firstResult = $(".pac-container .pac-item:first .pac-item-query").text();
                else
                    var firstResult = $(".pac-container .pac-item:first .pac-item-query").text() + ", " + $(".pac-container .pac-item:first span:eq(3)").text();

                var geocoder = new google.maps.Geocoder();
                geocoder.geocode({"address":firstResult }, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        placeName = results[0];
                        e.target.value = firstResult;
                        fillInAddress(placeName);
                        $('#datetimepicker1 .input-group-addon').click();
                    }
                });
            }

        });
    }

// [START region_fillform]
function fillInAddress(place) {
  // Get the place details from the autocomplete object.
  if(!place)
    var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;

    }
  }

}

答案 5 :(得分:0)

这是解决我问题的最简单方法:

autocomplete.addListener('place_changed', function() {
  if(event.keyCode == 13 || event.keyCode == 9) { // detect the enter key
    var firstValue = $(".pac-container .pac-item:first").text(); // assign to this variable the first string from the autocomplete dropdown
     }
    $('#search-address').val(firstValue); // add this string to input
    console.log(firstValue); // display the string on your browser console to check what it is
   //(...) add the rest of your code here
  });
}

答案 6 :(得分:0)

如果您使用的是角度2,4、5和6 ,请在下面的链接中找到答案

Angular 6, AGM selects first address in google autocomplete

Angular AGM autocomplete first address suggestion

答案 7 :(得分:-1)

将input-element放在form-element之外。使用javascript填充表单。

document.getElementById("adress").value = place.formatted_address;

答案 8 :(得分:-1)

我做了一些工作,现在我可以使用角度js和角度自动完成模块强制从谷歌placces中选择第一个选项。
感谢kuhnza
我的代码

<form method="get" ng-app="StarterApp"  ng-controller="AppCtrl" action="searchresults.html" id="target" autocomplete="off">
   <br/>
    <div class="row">
    <div class="col-md-4"><input class="form-control" tabindex="1" autofocus g-places-autocomplete force-selection="true"  ng-model="user.fromPlace" placeholder="From Place" autocomplete="off"   required>
    </div>
        <div class="col-md-4"><input class="form-control" tabindex="2"  g-places-autocomplete force-selection="true"  placeholder="To Place" autocomplete="off" ng-model="user.toPlace" required>
    </div>
    <div class="col-md-4"> <input class="btn btn-primary"  type="submit" value="submit"></div></div><br /><br/>
    <input class="form-control"  style="width:40%" type="text" name="sourceAddressLat" placeholder="From Place Lat" id="fromLat">
    <input class="form-control"  style="width:40%"type="text" name="sourceAddressLang" placeholder="From Place Long" id="fromLong">
    <input class="form-control"  style="width:40%"type="text" name="sourceAddress" placeholder="From Place City" id="fromCity">
    <input class="form-control"  style="width:40%"type="text" name="destinationAddressLat" placeholder="To Place Lat" id="toLat">
    <input class="form-control"  style="width:40%"type="text" name="destinationAddressLang" placeholder="To Place Long"id="toLong">
    <input class="form-control"  style="width:40%"type="text" name="destinationAddress"placeholder="To Place City" id="toCity">
</form>

这是Plunker
谢谢。