Terente
Terente

Reputation: 91

Wrap Google Places Autocomplete Service through jQuery UI Autocomplete feature

I am trying to use jQuery UI Autocomplete feature in order to make a wrapper of Google Autocomplete Service(because I just want to restrict some of the results returned by Google in a manner that is not possible through Google API).

Suppose I have this code:

$("#address").autocomplete({
  source: function(request, response){
    autoCompleteService = new google.maps.places.AutocompleteService();
    autoCompleteService.getQueryPredictions({input: request.term }, autocompleteCallback);
    //I should somewhere call the "response" object with desired suggestions as arguments
  },
  minLength: 5,
});

The problem is that jQuery UI Autocomplete forces me to call the "response" object(which is actually a function) with the suggestions I would like to show to the user as parameters.

But, on the other hand, Google API forces me to define a callback function(in my case 'autocompleteCallback') to whom it gives the requested suggestions as parameters after it's done.

Of course, I can't call the 'response' object inside the 'autocompleteCallback' function, and I can't call the response object just after this line either:

autoCompleteService.getQueryPredictions({input: request.term }, autocompleteCallback);

Because JS is async and I couldn't be sure that I get something in let's say: a global variable that I use in order to pass the results.

What would be the solution for that? Is there a well-known JS design pattern for a problem like this?

Upvotes: 2

Views: 3447

Answers (1)

Alexandra
Alexandra

Reputation: 4853

You, sir, are a genius to combine the two frameworks! So I'll share the solution that I have:

$("#search").autocomplete({
    source: function (request, response) {
        autoCompleteService.getQueryPredictions({ input: request.term }, function (predictions, status) {
            if (status != google.maps.places.PlacesServiceStatus.OK) {
                alert(status);
                return;
            }
            response($.map(predictions, function (prediction, i) {
                return {
                    label: prediction.description,
                    value: prediction.description
                }
            }));
        });
    },
    select: function (event, ui) {
        var value = ui.item.value;
        searchMap(value);
    }
});

Of course, I have an actual function that does the proper Place lookup (searchMap()) that takes in a term. The only realistic way to do this in order to have a proper autocompleteCallback AND response handler for jQuery UI autocomplete is to keep the callback implementation inline. It sucks if you want to do this in more than one place but I haven't thought of anything better. Yet...

Upvotes: 7

Related Questions