Google 地图 Places API V3 自动完成 - 在输入时选择第一个选项 [英] Google maps Places API V3 autocomplete - select first option on enter
问题描述
我已经按照 http://web.archive.org/web/20120225114154/http://code.google.com:80/intl/sk-SK/apis/maps/documentation/javascript/places.html.它工作得很好,但是我很想知道如何让它在用户按下 Enter 键时从建议中选择第一个选项.我想我需要一些 JS 魔法,但我对 JS 很陌生,不知道从哪里开始.
I have successfuly implemented Google Maps Places V3 autocomplete feature on my input box as per http://web.archive.org/web/20120225114154/http://code.google.com:80/intl/sk-SK/apis/maps/documentation/javascript/places.html. It works nicely, however I would love to know how can I make it select the first option from the suggestions when a user presses enter. I guess I would need some JS magic, but I am very much new to JS and don't know where to start.
提前致谢!
推荐答案
我在最近工作的网站上实现自动完成时遇到了同样的问题.这是我想出的解决方案:
I had the same issue when implementing autocomplete on a site I worked on recently. This is the solution I came up with:
$("input").focusin(function () {
$(document).keypress(function (e) {
if (e.which == 13) {
var firstResult = $(".pac-container .pac-item:first").text();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({"address":firstResult }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat(),
lng = results[0].geometry.location.lng(),
placeName = results[0].address_components[0].long_name,
latlng = new google.maps.LatLng(lat, lng);
$(".pac-container .pac-item:first").addClass("pac-selected");
$(".pac-container").css("display","none");
$("#searchTextField").val(firstResult);
$(".pac-container").css("visibility","hidden");
moveMarker(placeName, latlng);
}
});
} else {
$(".pac-container").css("visibility","visible");
}
});
});
http://jsfiddle.net/dodger/pbbhH/
这篇关于Google 地图 Places API V3 自动完成 - 在输入时选择第一个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!