Search code examples
javascriptjquerygoogle-apigoogle-custom-search

How do I repeat a query?


I need to repeat the following query in order to increase the results of google images. The code is executed after clicking on a button.

Google docs says:

Google Custom Search and Google Site Search return up to 10 results per query. If you want to display more than 10 results to the user, you can issue multiple requests (using the start=0, start=11 ... parameters) and display the results on a single page. In this case, Google will consider each request as a separate query, and if you are using Google Site Search, each query will count towards your limit.

Other SO question says

To get more result you should make multiple calls. in each different call, increase the value of parameter 'start' by 10.

And also this one says:

Now you can not ask google for more than 10 results at a time. So you have to query again asking for 10 result starting from 11. So In next query, keep num=10 and start=11. Now you can get all the results by changing start value.

How can I repeat the following and increase the start parameter each time?

    function googleImages() {
        var myCx = "MY_CX";
        var myKey = "MY_KEY";
        $.getJSON("https://www.googleapis.com/customsearch/v1", {
            q: termS + " in 1930 in " + country,
            alt: "json",
            searchType: "image",
            cx: myCx,
            num: 10,
            start: 0,
            key: myKey,
            rights: "cc_publicdomain",
            filter: "1",
            safe: "high",
            imgType: "photo",
            fileType: "jpg"
        },
        function (data) {
            $.each(data.items, function(i,item) {    
                $(".my_images .row .grid").append('<div class="col-sm-4 grid-item"><div class="thumbnail"><img class="img-responsive" src="' + item.link + '"></div></div>');
            });
            var $grid = $('.grid').packery({
            // options
            itemSelector: '.grid-item',
            percentPosition: true
        });
        $grid.imagesLoaded().progress( function() {
            $grid.packery('layout');
        });
        });
    }

Solution

  • You should save start value between calls so as example you could use pattern like this:

       function createGoogleImagesLoader(initialValue) {
           var _start = initialValue || 0;
           var imagesCount = 10;
    
           return function() {
                $.getJSON("https://www.googleapis.com/customsearch/v1", {
                    ...
                    num: imagesCount,
                    start: _start
                 },..);
                _start += imagesCount;
    
           }
        }
    
    var googleImages = createGoogleImagesLoader();
    googleImages() // load from 0 to 10
    googleImages() // load from 10 to 20 etc.