Google 地图 Places API V3 自动完成 - 在输入时选择第一个选项(并保持这种状态) [英] Google maps Places API V3 autocomplete - select first option on enter (and have it stay that way)

查看:13
本文介绍了Google 地图 Places API V3 自动完成 - 在输入时选择第一个选项(并保持这种状态)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题与这个问题的答案有关:Google 地图 Places API V3 自动完成 - 在输入时选择第一个选项.基本上,当用户按下 Enter 键时,它使该字段使用自动完成列表中的第一个建议.这个问题的答案有一个 jsfiddle - http://jsfiddle.net/dodger/pbbhH/- 除非文本字段失去焦点,否则该字段值会返回到部分输入的值.

This question relates to the answer for this one: Google maps Places API V3 autocomplete - select first option on enter. Basically, it is to make the field use the first suggestion from the autocomplete list when the user presses enter. The answer for that question has a jsfiddle - http://jsfiddle.net/dodger/pbbhH/ - which works except when the text field loses focus, the field value returns to the partially entered value.

例如,用户在输入字段中点击并输入ox",自动完成框弹出一些建议,用户按下回车键.然后更改地图以显示自动完成框(带有标记)中第一项的位置,并且输入字段的值更改为自动完成框中的第一项.然后用户单击字段外的某处,输入字段的值返回到ox".

For example, a user clicks in the input field and types 'ox', the autocomplete box pops up with some suggestions, and the user presses enter. The map is then changed to show the location of the first item from the autocomplete box (with a marker), and the value of the input field is changed to the first item from the autocomplete box. The user then clicks somewhere outside the field and the value of the input field returns to 'ox'.

我希望将输入字段的值保留为第一个自动完成建议.

I would like the value of the input field to stay as the first autocomplete suggestion.

推荐答案

试试这个:http://jsfiddle.净/pbbhH/60/

基本上将选择逻辑抽象为一个新函数selectFirstResult().然后在按下 Enter 键和失去对文本的关注时调用此函数.

Basically abstracted the selection logic to a new function selectFirstResult(). Then called this function on both pressing enter and losing focus on text.

 function selectFirstResult() {
    infowindow.close();
    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);

            moveMarker(placeName, latlng);
            $("input").val(firstResult);
        }
    });   
 }

根据@Ben 在下面的评论做了一些小改动.

made minor change per @Ben's comment below.

这篇关于Google 地图 Places API V3 自动完成 - 在输入时选择第一个选项(并保持这种状态)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆