Search code examples
javascriptimageapigoogle-custom-search

Filter Search Results For PNG images only


I copied most of the code from the Google docs, and then used the documentation to set the filter.

  • I don't get any errors
  • But the FILETYPE_PNG is not working (the filetype never gets restricted)

I used https://developers.google.com/custom-search/docs/structured_search#filetype

Does anybody know what's wrong with the code?

I also tried doing a searcher.execute("Kobe Bryant"); - but it still did not restrict to PNG only.

google.load('search', '1', {language: 'en', style: google.loader.themes.MINIMALIST});
google.setOnLoadCallback(function() {
  var customSearchOptions = {};
  var orderByOptions = {};
  orderByOptions['keys'] = [{label: 'Relevance', key: ''} , {label: 'Date', key: 'date'}];
  customSearchOptions['enableOrderBy'] = true;
  customSearchOptions['orderByOptions'] = orderByOptions;
  var imageSearchOptions = {};
  //imageSearchOptions['layout'] = LAYOUT_POPUP;  -- layout popup causing errors for some reason
  customSearchOptions['enableImageSearch'] = true;
  customSearchOptions['disableWebSearch'] = true;
  var customSearchControl =   new google.search.CustomSearchControl('Youaintfindingoutwhatthisis', customSearchOptions);
  customSearchControl.setResultSetSize(google.search.Search.SMALL_RESULTSET);

  var searcher = customSearchControl.getImageSearcher();
  searcher.setRestriction(
    customSearchControl.getImageSearcher.RESTRICT_FILETYPE,
    customSearchControl.getImageSearcher.FILETYPE_PNG
  );

  var options = new google.search.DrawOptions();
  options.setAutoComplete(true);
  customSearchControl.draw('cse', options);
}, true);

UPDATE

  • see my answer below

  • still don't know what's up with LAYOUT_POPUP - I get an undefined error here


Solution

  • Okay, I figured it out.

    The documentation is a little misleading.

    You need the following code to get filtering to work:

    customSearchControl.setSearchStartingCallback(
      this, function(control, searcher, query) {
          searcher.setQueryAddition("filetype:png OR filetype:PNG");
      }
    );
    

    Place this at the end of the js file. Hope this helps anyone else struggling with the documentation.