使用google maps autocomplete api和select2

时间:2018-03-07 15:59:21

标签: json parsing jquery-select2

我有一个关于使用select2实现Google Maps自动完成功能的问题。我在控制台中遇到此错误" Uncaught SyntaxError:意外的令牌:"。

$(document).ready(function() {
    $(".adress-autocomplete").select2({
        ajax: {
            url: "https://maps.googleapis.com/maps/api/place/autocomplete/json",
            type: "GET",
            dataType: 'jsonp',
            delay: 250,
            data: function (params) {
                return {
                    input: params.term, // search term
                    key: "MyKey"
                };
            },
            processResults: function (data, params) {
                params.page = params.page || 1;

                return {
                    results: data["predictions"],
                    pagination: {
                        more: (params.page * 2) < data.total_count
                    }
                };
            },
            cache: true
        },
        placeholder: 'Search Adress',
        escapeMarkup: function (markup) { return markup; }, 
        minimumInputLength: 2,
        templateResult: formatRepo,
        templateSelection: formatRepoSelection
    });

    function formatRepo (repo) {
        if (repo.loading) {
            return repo.text;
        }

        var markup = "<div class='select2-result-repository clearfix'>" +
            "<div class='select2-result-title'>" + repo.description + "</div>";


        return markup;
    }

    function formatRepoSelection (repo) {
        return repo.description;
    }
});

Json结果: https://jsonblob.com/1c69e57a-2220-11e8-b7b9-b3cbb530e512

1 个答案:

答案 0 :(得分:0)

Google不喜欢对其API的ajax请求,如果您覆盖Select2 dataAdapter并使用Google函数调用自动完成API,则会更好。

$.fn.select2.amd.define('select2/data/googleAutocompleteAdapter', ['select2/data/array', 'select2/utils'],
    function (ArrayAdapter, Utils) {
        function GoogleAutocompleteDataAdapter ($element, options) {
            GoogleAutocompleteDataAdapter.__super__.constructor.call(this, $element, options);
        }

        Utils.Extend(GoogleAutocompleteDataAdapter, ArrayAdapter);

        GoogleAutocompleteDataAdapter.prototype.query = function (params, callback) {
            var returnSuggestions = function(predictions, status)
            {
                var data = {results: []};
                if (status != google.maps.places.PlacesServiceStatus.OK) {
                    callback(data);
                }
                for(var i = 0; i< predictions.length; i++)
                {
                    data.results.push({id:predictions[i].place_id, text: predictions[i].description});
                }
                data.results.push({id:' ', text: 'Powered by Google', disabled: true});
                callback(data);
            };

            if(params.term && params.term != '')
            {
                var service = new google.maps.places.AutocompleteService();
                service.getPlacePredictions({ input: params.term }, returnSuggestions);
            }
            else
            {
                var data = {results: []};
                data.results.push({id:' ', text: 'Powered by Google', disabled: true});
                callback(data);
            }
        };
        return GoogleAutocompleteDataAdapter;
    }
);
function formatRepo (repo) {
    if (repo.loading) {
        return repo.text;
    }
    var markup = "<div class='select2-result-repository clearfix'>" +
        "<div class='select2-result-title'>" + repo.text + "</div>";
    return markup;
}

function formatRepoSelection (repo) {
    return repo.text;
}

var googleAutocompleteAdapter = $.fn.select2.amd.require('select2/data/googleAutocompleteAdapter');

$('.adress-autocomplete').select2({
    width: '100%',
    dataAdapter: googleAutocompleteAdapter,
    placeholder: 'Search Adress',
    escapeMarkup: function (markup) { return markup; }, 
    minimumInputLength: 2,
    templateResult: formatRepo,
    templateSelection: formatRepoSelection
});

https://jsfiddle.net/angelmarde/perqpp9f/2/

看起来您正在尝试按地址过滤,然后您可以更改此行:

service.getPlacePredictions({ input: params.term }, returnSuggestions);

添加类型

service.getPlacePredictions({ input: params.term, types: ['address'] }, returnSuggestions);

您可以在此处查看类型:https://developers.google.com/places/web-service/autocomplete#place_types