Feeds

Google Search with Ajax

Doing more things with the API

Combat fraud and increase customer satisfaction

We’ve all used Google to search the web. What if we could add Ajax to the web search operation? Google Ajax Search API does just that – could this facilitate searching?

Ajax is a web technique which refreshes content on a web page without reposting the web page and the Google Ajax Search API provides a search control and various searchers that can specialise a web search.

For example, using the Google Local Search service the web search may be localized to a specified region. Throw in a Google map and who needs to ask for directions? And the Google Blog search service is used to search only blogs.

Preliminary Setup

Before we can start using the Google Ajax Search API, we need to create a web application and register the URL of the web application with Google Ajax Search.

First download and install a web server to create and run the Google search application. We’ll use JDeveloper 10.1.3.2 with the embedded OC4J server to create our Google Ajax search web application.

Create a JDeveloper application and project with File>New>General>Application. Add a JSP, ajaxsearch.jsp, to the JDeveloper project with File>New>Web Tier>JSP>JSP. Select the default options in the Create JSP Wizard.

The directory structure of the new Google Search application is shown in Figure 1.

Illustration of Web Application for Google Ajax Search.

To obtain the URL for the ajaxsearch.jsp JSP right-click on the JSP and select Run. The URL for the ajaxsearch.jsp JSP is http://142.179.34.223:8990/GoogleAjaxSearch-GoogleAjaxSearch-context-root.

Next, we’ll register the URL with Google Ajax Search. Open the Sign up for the Google AJAX Search API page and specify the web application URL in the My web site URL field, and click on the Generate API Key button.

Ilustration of generating a Google Ajax Search API Key.

Sign in to the Google account (if not already signed in). A Google Ajax Search API key gets generated that may be used only for the web application for which the URL is registered. Similarly, obtain a Google Maps API key from the URL http://www.google.com/apis/maps/signup.html here. Save a copy of the Google Ajax Search API key and the Google Maps API key for use in the Google Ajax search application.

Overview of Google Ajax Search API

The main class of the Google Ajax search API is GSearchControl, which provides the user interface for a search performs the search using the different searcher objects. Some of the commonly used methods of the GSearchControl class are discussed in the following table.

Method Description
addSearcher Adds a searcher to the search control object.
draw Binds the search control object to the HTML container. The search results are displayed in a specified DOM element.
execute Initiates a search across the different searchers specified in the search control using a specified search term.
setResultSetSize Sets the result set size. Specifies the number of results in the result set. Values that may be specified are GSearch.LARGE_RESULTSET, which corresponds to 8 results, and GSearch.SMALL_RESULTSET, which corresponds to 4 results.
clearAllResults Clears all the search results from the search control.
setLinkTarget Specifies the link target for links embedded in search results. Default value is GSearch.LINK_TARGET_BLANK, which opens a link in a new window.
setSearchCompleteCallback Specifies a callback method that is invoked when the search is complete.
setSearchStartingCallback Specifies a callback method that is invoked when the search begins.

The search services are provided by “searchers”, which are represented by the GSearch class. The different searchers that are provided are discussed in following table.

Searcher Description
GwebSearch Provides the Google web search service. The search may be restricted to a specific web site, such as Expedia.com, using the setSiteRestriction method.
GlocalSearch Provides the local search service. The location for the search may be specified using GPoint, GMap or a string.
GvideoSearch Provides the Google Video Search service.
GblogSearch Provides the Google Blog Search Service.
GnewsSearch Provides the Google News Service.
GbookSearch Provides the Google Book Search service.

Some of the methods that are common to all searchers are setResultSetSize, clearResults, execute(query), setSearchCompleteCallback, setUserDefinedLabel, and setLinkTarget.

The setResultSetSize method sets the number of results returned by a searcher. The clearResults method clears the search results and resets the searcher. The setSearchCompleteCallback method registers a callback method on the searcher to be invoked when the search completes. The setUserDefinedLabel method sets a label for search result section, which replaces the default label “Local”, “Web”, or “Blog”. The setLinkTarget method specifies the link target for links in the search results. The default is to open the links a new browser window.

The search control displays the query results for the different searchers added to a search control object in one of the two draw modes: linear or tabbed. The linear draw mode is the default and is shown below in Figure 3.

Illustration showing Linear Draw Mode.

The tabbed draw mode is shown below in Figure 4.

Illustration of Tabbed Draw Mode.

The search results may be displayed in one of the three expansion modes: open, closed, or partial. In the open expansion mode the search results are displayed fully. In the closed mode the search results are not displayed until a UI element such as an arrow is clicked. The partial search result displays partial results. The default expansion mode is partial.

Creating a Google Ajax Search Application

In this section, we’ll create a Google Ajax Search application using the Google Local search service. To the ajaxsearch.jsp add the Google Ajax Search API JavaScript library. Specify the Google Ajax Search API key in the src attribute for the script tag.

Create a JavaScript function, onLoad(), to add a search control and search service. In the onLoad() function, create a search control object:

 var searchControl = new GSearchControl();

Set the result set size to GSearch.LARGE_RESULTSET, which typically returns 8 results:

 searchControl.setResultSetSize(GSearch.LARGE_RESULTSET); 

Create a GlocalSearch searcher object for the Google Local search service:

 var localSearch = new GlocalSearch();

Add the searcher to the search control:

 searchControl.addSearcher(localSearch); 

Set the location for which the local search is to be performed with the setCenterPoint(location) method:

 localSearch.setCenterPoint("London UK"); 

Create a GdrawOptions object to specify the draw options for the search results:

 var drawOptions = new GdrawOptions();

Set the draw mode to linear:

 drawOptions.setDrawMode(GSearchControl.DRAW_MODE_LINEAR); 

Specify a div element to display the search control results:

<div id="searchcontrol">Loading</div>

Activate the search control and display the results in the searchcontrol div:

 searchControl.draw(document.getElementById("searchcontrol")); 

Register the onLoad() function with the document using the setOnLoadCallback static method of the GSearch class. When the document has completed loading the onLoad() function will be invoked:

 GSearch.setOnLoadCallback(OnLoad); 

The ajaxsearch.jsp is listed below:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google AJAX Search</title>
    <link href="http://www.google.com/uds/css/gsearch.css" type="text/css"
          rel="stylesheet"/>
    <script  
src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=ABQIAAAAItAEL-H-GuOHsDfD7MxmlhT7mv 
5WRGU_VmTV_U7i6gk-knMDhxQ5YomdhRDg3KUS6GrAGkfOejZoCw"
            type="text/javascript"></script>

    <script language="Javascript" type="text/javascript">
    function OnLoad() {
      
      var searchControl = new GSearchControl();
      searchControl.setResultSetSize(GSearch.LARGE_RESULTSET);
      var localSearch = new GlocalSearch();
      searchControl.addSearcher(localSearch);
      
      localSearch.setCenterPoint("London UK");
      
      var drawOptions = new GdrawOptions();
      drawOptions.setDrawMode(GSearchControl.DRAW_MODE_LINEAR);
      searchControl.draw(document.getElementById("searchcontrol",drawOptions));
      
    }
    GSearch.setOnLoadCallback(OnLoad);
    </script>
  </head>
  <body><div id="searchcontrol">Loading</div></body>
</html>

Right-click on the ajaxsearch.jsp and select Run to run the JSP.

Illustration of running a Google Ajax Search application.

The Google Local search service page gets displayed. Specify a search term, for example “Auto Repair”, and click on Search. The Google Local search service searches only in the location specified by the setCenterPoint method of the GlocalSearch object.

Illustration of Google Ajax Search User Interface.

The search result gets displayed in expansion mode PARTIAL.

Illustration of search result.

To display all the search results click on show all results.

Illustration of all search results.

Next, we’ll add a Google Map to the Google Ajax Search. In the ajaxsearch.jsp JSP, we must include the Google Maps JavaScript library:

<script 
src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAItAEL-H-GuOHsDfD7MxmlhQ6c
Eu3Q11txNOPL7YQRWHJy8OKPxQE9Bi7QBtzNgr-yh4YZk2_RBO8DQ"
      type="text/javascript"></script>

We then create a marker to locate locations on the Google map:

var gSmallIcon = new GIcon();
gSmallIcon.image = "http://labs.google.com/ridefinder/images/mm_20_yellow.png";

On the Google web search page we create divs for the search form, the search results, and the Google map:

<body>
    <h1>Google Local Search</h1>
    <p>Search for locations on the map below and save them to your list.</p>
    <div id="placelist">
      <div id="search">
        <div id="searchform"></div>
      </div>
      <div id="results">
        <div id="searchwell"></div>
      </div>
      <div id="map"></div>
      <div id="selected"></div>
    </div>
  </body>

Create a search form with the GSearchForm class:

gSearchForm = new GSearchForm(false, document.getElementById("searchform"));

Register a method with the search form using the setOnSubmitCallback(object, method) method to be invoked when the form is submitted:

gSearchForm.setOnSubmitCallback(null, CaptureForm); 

Now, set the focus on the input:

gSearchForm.input.focus();

Initialize a Google Map and set the center location for the map:

gMap = new GMap(document.getElementById("map"));
gMap.addControl(new GSmallMapControl());
gMap.addControl(new GMapTypeControl());
gMap.setCenter(new GLatLng(51.5, -0.1167), 13); 

Initialize the Google local search object. Specify the center location for the local searcher and register a callback method to be invoked when the search completes:

gLocalSearch = new GlocalSearch();
gLocalSearch.setCenterPoint(gMap);
gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch); 

The complete application ajaxsearch.jsp for the Google Ajax search including a Google map is available in the resources zip file here. Run the Google Ajax Search/Map application similarly to the earlier application and a search form with a Google map is displayed.

Specify a search term, “Swiss Restaurant” for example, and click on the Search button:

Illustration of search form and map.

The search results get displayed with corresponding markers on the Google map:

Illustration of search result and map.

The Google Ajax Search API and the Google Maps API do therefore appear to facilitate Google web search, in answer to the question posed at the start of this tutorial.

For debugging, use a JavaScript debugger. For IE, use the Microsoft Script Debugger; but browser debugging is sometimes an issue, as some browsers do not have a debugging environment available (see also here). For further online information on Google Ajax search, refer to http://code.google.com/apis/ajaxsearch/documentation/ here.

High performance access to file storage

More from The Register

next story
Android engineer: We DIDN'T copy Apple OR follow Samsung's orders
Veep testifies for Samsung during Apple patent trial
This time it's 'Personal': new Office 365 sub covers just two devices
Redmond also brings Office into Google's back yard
Batten down the hatches, Ubuntu 14.04 LTS due in TWO DAYS
Admins dab straining server brows in advance of Trusty Tahr's long-term support landing
Microsoft lobs pre-release Windows Phone 8.1 at devs who dare
App makers can load it before anyone else, but if they do they're stuck with it
Half of Twitter's 'active users' are SILENT STALKERS
Nearly 50% have NEVER tweeted a word
Internet-of-stuff startup dumps NoSQL for ... SQL?
NoSQL taste great at first but lacks proper nutrients, says startup cloud whiz
Windows 8.1, which you probably haven't upgraded to yet, ALREADY OBSOLETE
Pre-Update versions of new Windows version will no longer support patches
Microsoft TIER SMEAR changes app prices whether devs ask or not
Some go up, some go down, Redmond goes silent
Red Hat to ship RHEL 7 release candidate with a taste of container tech
Grab 'near-final' version of next Enterprise Linux next week
Ditch the sync, paddle in the Streem: Upstart offers syncless sharing
Upload, delete and carry on sharing afterwards?
prev story

Whitepapers

Designing a defence for mobile apps
In this whitepaper learn the various considerations for defending mobile applications; from the mobile application architecture itself to the myriad testing technologies needed to properly assess mobile applications risk.
3 Big data security analytics techniques
Applying these Big Data security analytics techniques can help you make your business safer by detecting attacks early, before significant damage is done.
Five 3D headsets to be won!
We were so impressed by the Durovis Dive headset we’ve asked the company to give some away to Reg readers.
The benefits of software based PBX
Why you should break free from your proprietary PBX and how to leverage your existing server hardware.
Securing web applications made simple and scalable
In this whitepaper learn how automated security testing can provide a simple and scalable way to protect your web applications.