Finding Images on a Specific Site
March 8, 2010
One feature of the AJAX Image Search API that you might find useful is the ability to retrieve only the images which are visible on a specific website. For example, you could add a search box that allows people to search through just the images on your own site or you could create a slideshow which shows images from your favorite site.
To specify a site, use the setSiteRestriction
method on an ImageSearch
object. Here is a simple example:
http://code.google.com/apis/ajax/playground/#site_restrict
We can do more than just provide a site-specific image search box, we could also use the search results in a unique way. For example, we could create a slideshow which shows images which match our desired keyword and appear on a specific site. For this example, let's create a simple slideshow that displays images from nasa.gov.
var imageIndex = 0;
var images;
function nextImage() {
imageIndex++;
if (imageIndex >= images.length) {
imageIndex = 0;
}
var imageContainer = document.getElementById(
'image-container');
imageContainer.src = images[imageIndex].tbUrl;
}
function searchComplete(searcher) {
if (searcher.results && searcher.results.length > 0) {
var contentDiv = document.getElementById(
'content-slideshow');
contentDiv.innerHTML = '';
var imageTag = document.createElement('img');
imageTag['id'] = 'image-container';
imageTag['src'] = searcher.results[imageIndex].tbUrl;
images = searcher.results;
contentDiv.appendChild(imageTag);
// Switch to the next image every 5 seconds.
setInterval("nextImage();", 5000);
}
}
function slideshowOnLoad() {
var imageSearch = new google.search.ImageSearch();
imageSearch.setSiteRestriction('nasa.gov');
imageSearch.setSearchCompleteCallback(
this, searchComplete, [imageSearch]);
imageSearch.execute('supernova');
}
google.setOnLoadCallback(slideshowOnLoad);
In the above samples, there are three lines I'd like to call your attention to. The first line to note is the imageSearch.execute
at the bottom, here we've entered the keywords that our slideshow images should be related to. Next we restrict the site to nasa.gov using imageSearch.setSiteRestriction
. Lastly, we call setInterval
once we receive the results of our search for images. The setInterval
call tells the browser to run our nextImage
function every five seconds.
Here are the two samples we've talked about in action:
The site restriction can also include a path within a website. For example you could do setSiteRestriction(
to search the photos that have been posted by a particular user on flickr.
'http://www.flickr.com/photos/<username>')
To learn more about some other neat features of the AJAX Image Search API take a look at our code playground samples and documentation. For questions on this and other topics, drop us a line in the discussion group.