AngularJS has ngAutoComplete that works with Google place perfectly.
How can I make it work with Google Suggest API (the suggested keywords when typing in Google Search input box)? Is there something out of the box?
If not, what is the best way to implement it? (if I need my own API interface - how should I make the connection)?
EDITED
Google Suggest API will return XML for the following call. If I want to return JSON it needs to be passed via my server side to translate it. It could also be an option if you suggest so
http://google.com/complete/search?output=toolbar&q=theory&gl=in
You can add this to the remote-url -
https://www.google.com/s?sclient=psy-ab&biw=1242&bih=395&q=
ThisIsTheSearchString&oq=&gs_l=&pbx=1&bav=on.2,or.r_cp.&bvm=bv.93112503,d.cWc&fp=160df26a97fa030e&pf=p&sugexp=msedr&gs_rn=64&gs_ri=psy-ab&tok=_1hxlqgFnvRgVdHXR4t-nQ&cp=10&gs_id=51&xhr=t&es_nrs=true&tch=1&ech=37&psi=O5FTVZiMAfPisASwnYH4Cg.1431540027601.1
Make ThisIsTheSearchString a var that changes on key stroke. Before you put the url into the ngAutoComplete make sure to encode the string - escape(ThisIsTheSearchString);
This will help if there are any white spaces in the search.
I got the URL by going to google and watching the network tab. It will return a .txt file that you will have to read. Also you will need a regex to compile the file.
Directive performs much better because on keyup
performs a http
call to GoogleSuggest API
elem.bind('keyup', scope.search);
Markup:
<div data-ng-google-suggest ng-model="Search"></div>
Note: I plan to make a GitHub repo for ngGoogleSuggest
after it has been tested a bit more
Screen Shots
Calling Google Search API
'http://suggestqueries.google.com/complete/search
&client=firefox
?callback=JSON_CALLBACK
to avoid Access-Control-Allow-Origin Error
example $http
call
scope.search = function() {
// If searchText empty, don't search
if (scope.searchText == null || scope.searchText.length < 1)
return;
var url = 'http://suggestqueries.google.com/complete/search?';
url += 'callback=JSON_CALLBACK&client=firefox&hl=en&q='
url += encodeURIComponent(scope.searchText);
$http.defaults.useXDomain = true;
$http({
url: url,
method: 'JSONP',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).
success(function(data, status, headers, config) {
// Api returns [ Original Keyword, Searches[] ]
var results = data[1];
if (results.indexOf(scope.searchText) === -1) {
data.unshift(scope.searchText);
}
scope.suggestions = results;
scope.selectedIndex = -1;
}).
error(function(data, status, headers, config) {
console.log('fail');
// called asynchronously if an error occurs
// or server returns response with an error status.
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With