【问题标题】:Filter results from Google Autocomplete过滤来自 Google 自动填充的结果
【发布时间】:2014-08-02 20:58:15
【问题描述】:

有没有办法在结果显示在输入下方之前从 Google Autocomplete API 获取结果?我想显示除美国以外的任何国家/地区的结果。

我发现了这个问题:Google Maps API V3 - Anyway to retrieve Autocomplete results instead of dropdown rendering it? 但它没有用,因为方法 getQueryPredictions 只返回 5 个元素。

这是英国和美国结果的示例:http://jsfiddle.net/LVdBK/

有可能吗?

【问题讨论】:

  • 我不知道你是怎么做到的。您可以将搜索限制在特定国家或特定范围as described here,但不能从结果中排除国家。您可以随时发送feature request
  • @MrUpsidown 已经有人建议:code.google.com/p/gmaps-api-issues/issues/detail?id=4233 2 年前..
  • 嗯,这并不完全一样(仅限于多个国家与排除一个国家(或多个国家顺便说一句。))但无论如何,这个问题现在已经快 2 年了,感觉不像正在为此做任何事情......无论如何记录另一个功能请求取决于您。

标签: google-maps-api-3 autocomplete


【解决方案1】:

我使用了 jquery 自动完成小部件并手动调用了 google 方法。

对于我们的案例,我们只想显示美国密歇根州的地址。 由于 Google 不允许过滤掉这种程度的响应,因此您必须手动进行。

  1. 覆盖 jquery 自动完成的源函数
  2. 调用google autocompleteService.getQueryPredictions 方法
  3. 过滤掉您想要的结果,并将它们作为 jquery 自动完成的“响应”回调返回。

或者,如果您需要有关 Google 所选项目的更多详细信息,请覆盖 jquery 自动完成的选择功能并调用 Google 的 PlacesService.getDetails 方法。

以下假设您拥有“places”库的 Google api 参考。

<script src="https://maps.googleapis.com/maps/api/js?key=[yourKeyHere]&libraries=places&v=weekly" defer></script>
var _autoCompleteService; // defined globally in script
var _placesService; // defined globally in script

//...

// setup autocomplete wrapper for google places 

// starting point in our city
    var defaultBounds = new google.maps.LatLngBounds(
         new google.maps.LatLng('42.9655426','-85.6769166'),
         new google.maps.LatLng('42.9655426','-85.6769166'));

   
    if (_autoCompleteService == null) {
        _autoCompleteService = new google.maps.places.AutocompleteService();
    }
    
    $("#CustomerAddress_Street").autocomplete({
        minLength: 2,
        source: function (request, response) {
            if (request.term != '') {
                var googleRequest = {
                    input: request.term,
                    bounds: defaultBounds,
                    types: ["geocode"],
                    componentRestrictions: { 'country': ['us'] },
                    fields: ['geometry', 'formatted_address']
                }
                _autoCompleteService.getQueryPredictions(googleRequest, function (predictions) {
                    var michiganOnly = new Array(); // array to hold only addresses in Michigan
                
                    for (var i = 0; i < predictions.length; i++) {
                        if (predictions[i].terms.length > 0) {
                            // find the State term. Could probably assume it's predictions[4], but not sure if it is guaranteed.
                            for (var j = 0; j < predictions[i].terms.length; j++) {
                                if (predictions[i].terms[j].value.length == 2) {
                                    if (predictions[i].terms[j].value.toUpperCase() == 'MI') {
                                        michiganOnly.push(predictions[i]);
                                    }
                                }
                            }
                        }
                    }
                    response(michiganOnly);
                });
            }
        },
        select: function (event, ui) {
            if (ui != null) {
                var item = ui.item;
                var request = {
                    placeId: ui.item.place_id
                }

                if (_placesService == null) {
                    $("body").append("<div id='GoogleAttribution'></div>"); // PlacesService() requires a field to put it's attribution image in. For now, just put on on the body
                    _placesService = new google.maps.places.PlacesService(document.getElementById('GoogleAttribution'));
                }
                _placesService.getDetails(request, function (result, status) {
                    if (result != null) {
                        const place = result;
                        
                        if (!place.geometry) {
                            // User entered the name of a Place that was not suggested and
                            // pressed the Enter key, or the Place Details request failed.
                            //window.alert("No details available for input: '" + place.name + "'");
                            return;
                        }
                        else {
                            var latitude = place.geometry.location.lat();
                            var longitude = place.geometry.location.lng();
                        // do something with Lat/Lng
                        }
                    }
                });
            }
        }

    }).autocomplete("instance")._renderItem = function (ul, item) {
    // item is the prediction object returned from our call to getQueryPredictions
    // return the prediction object's "description" property or do something else
        return $("<li>")
            .append("<div>" + item.description + "</div>")
            .appendTo(ul);
    };
    $("#CustomerAddress_Street").autocomplete("instance")._renderMenu = function (ul, items) {
    // Google's terms require attribution, so when building the menu, append an item pointing to their image
        var that = this;
        $.each(items, function (index, item) {
            that._renderItemData(ul, item);
        });
        $(ul).append("<li class='ui-menu-item'><div style='display:flex;justify-content:flex-end;'><img src='https://maps.gstatic.com/mapfiles/api-3/images/powered-by-google-on-white3.png' /></div></li>")
    }

【讨论】:

    猜你喜欢
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 2012-11-20
    • 2021-11-04
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多