首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >谷歌地图放置API V3自动完成-在回车时选择第一个选项

谷歌地图放置API V3自动完成-在回车时选择第一个选项
EN

Stack Overflow用户
提问于 2011-10-23 17:54:38
回答 14查看 130.7K关注 0票数 74

我已经成功地按照http://web.archive.org/web/20120225114154/http://code.google.com:80/intl/sk-SK/apis/maps/documentation/javascript/places.html在我的输入框中实现了Google Maps Places V3 autocomplete功能。它工作得很好,但是我想知道当用户按回车键时,如何让它从建议中选择第一个选项。我想我需要一些JS魔法,但我对JS非常陌生,不知道从哪里开始。

提前感谢!

EN

回答 14

Stack Overflow用户

回答已采纳

发布于 2011-11-17 03:03:29

在我最近工作的一个网站上实现自动完成时,我也遇到了同样的问题。这是我想出的解决方案:

代码语言:javascript
复制
$("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/

票数 47
EN

Stack Overflow用户

发布于 2013-07-07 00:48:47

这是一个真实的,非黑客的解决方案的例子。它没有使用任何浏览器黑客等,只使用来自谷歌提供的公共API的方法,文档如下:Google Maps API

唯一的缺点是,如果用户没有从列表中选择一个项目,则需要向Google发出额外的请求。优点是结果总是正确的,因为查询的执行方式与AutoComplete中的查询完全相同。第二个好处是,通过只使用公共API方法,而不依赖于AutoComplete小部件的内部超文本标记语言结构,我们可以确保,即使谷歌进行更改,我们的产品也不会崩溃。

代码语言:javascript
复制
var input = /** @type {HTMLInputElement} */(document.getElementById('searchTextField'));
var autocomplete = new google.maps.places.Autocomplete(input);  
// These are my options for the AutoComplete
autocomplete.setTypes(['(cities)']);
autocomplete.setComponentRestrictions({'country': 'es'});

google.maps.event.addListener(autocomplete, 'place_changed', function() {
    result = autocomplete.getPlace();
    if(typeof result.address_components == 'undefined') {
        // The user pressed enter in the input 
        // without selecting a result from the list
        // Let's get the list from the Google API so that
        // we can retrieve the details about the first result
        // and use it (just as if the user had actually selected it)
        autocompleteService = new google.maps.places.AutocompleteService();
        autocompleteService.getPlacePredictions(
            {
                'input': result.name,
                'offset': result.name.length,
                // I repeat the options for my AutoComplete here to get
                // the same results from this query as I got in the 
                // AutoComplete widget
                'componentRestrictions': {'country': 'es'},
                'types': ['(cities)']
            },
            function listentoresult(list, status) {
                if(list == null || list.length == 0) {
                    // There are no suggestions available.
                    // The user saw an empty list and hit enter.
                    console.log("No results");
                } else {
                    // Here's the first result that the user saw
                    // in the list. We can use it and it'll be just
                    // as if the user actually selected it
                    // themselves. But first we need to get its details
                    // to receive the result on the same format as we
                    // do in the AutoComplete.
                    placesService = new google.maps.places.PlacesService(document.getElementById('placesAttribution'));
                    placesService.getDetails(
                        {'reference': list[0].reference},
                        function detailsresult(detailsResult, placesServiceStatus) {
                            // Here's the first result in the AutoComplete with the exact
                            // same data format as you get from the AutoComplete.
                            console.log("We selected the first item from the list automatically because the user didn't select anything");
                            console.log(detailsResult);
                        }
                    );
                }
            }
        );
    } else {
        // The user selected a result from the list, we can 
        // proceed and use it right away
        console.log("User selected an item from the list");
        console.log(result);
    }
});
票数 22
EN

Stack Overflow用户

发布于 2014-01-14 05:25:52

似乎有一个更好、更干净的解决方案:用google.maps.places.SearchBox代替google.maps.places.Autocomplete。代码几乎是一样的,只是从多个地方得到第一个。一按Enter键,就会返回正确的列表--这样它就会在开箱即用,不需要修改。

请参阅示例HTML页面:

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

相关的代码片段是:

代码语言:javascript
复制
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

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7865446

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档