Close Window

Print Story

Working with the Google AJAX Feed API

As you may know, one of the most compelling features of the Internet has been the explosion in the use of Internet feeds. Internet feeds serve as an extremely useful way to syndicate pure data in XML, as opposed to classical HTML Web pages where the data is intermixed with the user interface. Due to its simplicity, there are now literally millions of Internet feeds available with myriad data like the weather, news, and blogs.

Historically the only downside was that interacting directly with Internet feed data was somewhat complex because you had to extract and parse the XML feed data for display. Typically this was done using server-side technologies such as Java and PHP.

With Google's AJAX Feed API, however, pulling down Internet feed data and integrating it into your Web pages has never been so easy! It's like Google's Maps API, where all you need is a bit of JavaScript code on your page and you instantly have a usable Map. With a bit of JavaScript on your page, you can easily integrate Internet feed data into your Web pages.

In Figure 1, the Blogroll and Photos content on the right is derived from Internet feeds. This is easily doable in just a few lines of JavaScript. Before jumping into examples of Google's AJAX Feed at work, let's review a bit the Feed API's architecture.

The AJAX Feed API's Architecture at a Glance
Google's AJAX Feed API is a combination of a hosted service provided by Google along with a lightweight JavaScript client API that allows for the easy integration of public RSS and Atom feeds into any Web page via JavaScript. At its core, the AJAX Feed API relies on a Google service known as FeedFetcher that continuously scours the Internet for feeds and caches them on Google's worldwide servers, similar to how Google caches all other Internet data. Since feed data is constantly updated, the FeedFetcher is constantly refreshing its caches with fresh data.

As the feed data is cached on Google's servers, the AJAX Feed JavaScript API provides an easy way for a client Web page to make requests and pull down any feed data. The API does this by injecting a script tag onto the client page, which then makes the feed data request directly from Google without violating the same origin security policy. The API has provisions for the user to specify a callback function so when the request is complete it will call the provided callback function that can render the feed data. The user-provided callback function can either be low-level JavaScript code that iterates through the raw feed data and updates the user interface via DOM methods, or it can be just a few lines calling one of the available higher-level controls such as the FeedControl or the feed SlideShow. The overall AJAX Feed architecture is displayed in Figure 2.

The AJAX Feed API provides flexible ways to display feed data. At a low level, it provides both JSON and/or XML output to the Web page. The JSON output is a unified, or canonicalized, output of data from the original RSS or Atom feeds. Why is it canonicalized? This is done to provide a single way of extracting feed data as opposed to having to parse the different feeds separately because of their different RSS and Atom specifications. With the unified feed elements, it's easy to work with multiple feeds of multiple formats using the same code. (Figure 3)

Using the AJAX Feed API
To get a feel for how to work with the AJAX Feed, let's review some basic examples for starters. As mentioned earlier, the AJAX Feed API is a JavaScript API that communicates with Google's worldwide servers to provide feed data to your client Web page. As with the other JavaScript APIs that Google provides, one first has to get the API key that's issued after agreeing to a Terms of Services document. Once you have your API key, you can begin coding in JavaScript and build your first example such as a HelloWorld. In fact, Google provides some initial examples to help you get started.

An AJAX Feed HelloWorld Example
There's a simple HelloWorld example in Listing 1 that illustrates how to download an Internet feed from digg.com and display some of its data on a Web page.

In that example, we see how to load the AJAX Feed API using the new common loader syntax by specifying both the name of the API ("feeds") and its version ("1"). Incidentally the other AJAX APIs, AJAX Search and Google Maps also support this syntax.

After loading the Feed API, a function called initialize( ) is defined. This function creates a new google.feeds.Feed instance and specifies that it should load the feed located at www.digg.com/rss/index.html. The remainder of the function establishes an in-line callback function to process the returned data. Since no data type is specified, the default data is in JavaScript's native JSON format and is loaded into the result object. The remainder simply iterates through the data in the result object and uses the DOM methods, createElement( ), createTextNode( ), and appendChild( ) to write the returned feed data directly to the parent document by putting it inside of the empty <div> element with id="feed."

Figure 4 shows how the HelloWorld example will render in a browser.

Extending the HelloWorld Example - Displaying Multiple Feeds
As you get more familiar with the AJAX Feed API, you'll find it quite easy to display the returned data in more interesting ways. For example, here's an example that illustrates how multiple feeds in different formats will display in the same manner. This page is merely an extended version of the HelloWorld example above that lets the user select or enter his own Feed URL. In stepping through this demo, you see how the AJAX Feed API provides unified access to any supported RSS or Atom feed without having to parse them independently.

As you can see in Figure 5, it displays the BBC's RSS News Feed. Figure 6 shows the same Web page but pointing to a different feed URL. In this case it's Yahoo's Weather Feed.

Creating a page that displays feed data this way is relatively straightforward. We have a portion of the relevant code from this example. Aside from a standard HTML form on the page, there's an empty portion beneath the form that's populated dynamically by calling the JavaScript function showFeed( ). This function accepts a feed URL passed from the HTML form.

The code that populates the lower part of the page is in Listing 2.

You can see in the code that, as the showFeed( ) function is executed, it first creates a new Feed object with the chosen feedURL passed to it from the HTML form. The rest of the code works to display the feed data using DOM methods. First it displays core feed information such as the title, link, description, and author. These are attached to an existing <div> with id = "banner-div." It then generates an HTML table dynamically to display the repeating feed data from the entries array and attaches it to an existing <div> with id="feed-div."

Displaying Feed Data More Compellingly - GeoCoded Photos on a Google Map
Dumping feed data into an HTML table is somewhat interesting, however there are more interesting and compelling ways to display feed data. For example, it's possible to use the AJAX Feed API to extract geo-encoded data and then display it on a Google Map.

Here's a fun mash-up where the AJAX Feed API extracts geo-encoded photos from a feed and then uses the Google Maps API to display the data.

As shown in Figure 7, this example displays photos that correspond to one or a set of tags. In this case the single tag, "Paris," is used as a query parameter to the Flickr photo feed: http://api.flickr.com/services/feeds/photos_public.gne?tags=geo,paris&georss=true

Also notice that an additional parameter, "georss=true," is also provided. This triggers the feed to supply only photos that are geo-encoded in the feed.

The raw data with the pertinent parts highlighted as it is returned from the feed is in Listing 3. You'll see that this feed contains a series of entries that have both HTML snippets in <content> tags and latitude and longitude information encoded in a <geo:Point> tag.


The JavaScript code responsible for extracting the feed information and putting it in an array of Google Map points is in Listing 4.

The important thing to notice in the code is the statement: feed.setresultFormat(googlefeeds.Feed.MIXED_FORMAT);. This statement allows for the extraction of both JSON and extra XML data at the same time. In our case this is important because the <geo:lat> and <geo:long> tags are extracted and assigned to the variables latnode and longnode. Its actual text content is then used to create a new Google Map point (using the constructor for GLatLng( )). Then it's pushed into an array of Google Maps points (mapPoints) that are displayed on a Google Map using the function showMap( ).

The code for showMap( ) isn't shown but is similar to many basic Google Maps API examples where an array of Map points are displayed with pop-up windows that contain HTML content. You can see examples on how to do this at www.google.com/apis/maps/documentation/examples/index.html.

To see a live demo go to http://gmaps-samples.googlecode.com/svn/trunk/ajaxfeed-flickr.html.

AJAX Feed Controls
The code examples so far involve a fair amount of JavaScript code to iterate through feed data and display it dynamically. However, if you simply need to display text or image data from a feed in a neatly formatted box on your Web page with minimal coding then using one of the AJAX feed controls with their efficient coding approach is definitely recommended.

Using the FeedControl
The first AJAX API Feed control worthy of attention is the AJAX Feed API control. The AJAX Feed API FeedControl provides a neat solution for Web page authors who want to present the text from one or multiple feeds in a stacked or tabbed HTML box without having to write a lot of JavaScript code as shown in Listing 5.

Figure 8 shows how the FeedControl renders. You'll notice that in the draw( ) method, there's a second argument with options for the FeedControl. In this case, it specifies render the control with tabbed bars. The default is to render multiple feeds in a stacked linear manner. The FeedControl also provides a setNumEntries( ) method that specifies how many feed results to display. And, finally, another feature of the FeedControl worth mentioning is its setLinkTarget( ) method, which defines the link target of the feed links rendered by the FeedControl. This lets you control whether clinking the links rendered in the FeedControl opens a new window, current window, top frame, or replace the current frame.

The FeedControl display is governed by a set of CSS styles that's well documented on the AJAX API Feed's homepage on the code.google.com Web site. A base look and feel stylesheet comes as a default with the FeedControl and to customize it, you merely override the default styles in your Web page.

Using the SlideShow Control
In contrast to offering an easy solution to display textual data from an Internet feed, the SlideShow (GFslideShow) control displays photos from Internet feeds in a slideshow format. The code to add this control to your page is also minimal.

...
    google.load("feeds", "1");

    function LoadSlideShow() {
      var feed = "http://feed.photobucket.com/images/sunsets/feed.rss";
      var options = {displayTime:2000, transitionTime:600, scaleImages:true};
      new GFslideShow(feed, "slideShow", options);
    }

    google.setOnLoadCallback(LoadSlideShow);

This code renders as shown in Figure 9. The SlideShow controls can pause a show by clicking a pause button that appears when you hover over the image. Some of the options that you can specify are the time that each image will show (displayTime), the time it takes to transition between images (transitionTime), the number of images to loop through (numResults), and whether or not to scale the images to the actual size of the control.

Using Feed Discovery
So far, all of the AJAX Feed examples have included known feed URLs. There are instances, however, when you may want to offer the user the ability to search for feeds on-the-fly. In this case you can use the AJAX Feed API's new Feed Discovery feature. Using it is a simple process of passing a query string as well as a callback function to a method, findFeeds( ) and it will return a set of results as an array of feed URLs with their respective titles. The results array can then be iterated through and have their feeds applied to a FeedControl. Listing 6 is a sample that queries feeds that are associated with the term "AJAX."

The results of the "AJAX" query returns the following feeds shown in Figure 10 that were displayed in a FeedControl in stacked display mode.

Summary
Having stepped through the various uses of the AJAX Feed API, you can see that it offers a wealth of functionality to a diverse audience. For those comfortable with JavaScript and DOM programming, the AJAX Feed API doesn't get in the way! Instead it empowers power developers in building completely custom solutions with Internet feed data.

On the other hand, for those who'd rather not get too deep into JavaScript programming, the easy-to-use advanced controls such as FeedControl and SlideShow offer complete and polished solutions with minimal coding.

For more information on Google AJAX APIs check out Google's API technology Web site at http://code.google.com or more specifically see http://code.google.com/apis/ajaxfeeds/. You'll see detailed documentation along with many helpful samples that will help you get started in minutes.

© 2008 SYS-CON Media Inc.