Hacking Google Maps and Google Earth (ExtremeTech)

(Dana P.) #1

Chapter 4 — The Google Web API 63


Printing out the information is, therefore, quite straightforward: You just dump out the infor-
mation in the hash, and then progress through each item in the array and print out the individ-
ual result fields to get the information you want.


You can also see here that the title and snippet fields of each result are in encoded HTML. For
example, the angle brackets (<>) that normally identify a tag are instead included in HTML-
encoded format. The reformat function in Listing 4-1 uses a regular expression to convert these
back into angle brackets so that they are correctly displayed as HTML.


Java


With Java, the easiest method is to use the Javaclass supplied with the Google API (see
Listing 4-3).


Listing 4-3:A Java Code Example

import com.google.soap.search.;
import java.io.
;


public class GMapsAPISearch {
public static void main(String[] args) {


String Key = “XXX”;

GoogleSearch s = new GoogleSearch();
s.setKey(Key);

try {
s.setQueryString(args[0]);
GoogleSearchResult r = s.doSearch();
System.out.println(“ Results:”);
System.out.println(r.toString());
} catch (GoogleSearchFault f) {
System.out.println(“Search failed:”);
System.out.println(f.toString());
}
}
}


The class is quite straightforward to use. You must first change the API key to the one pro-
vided to you in e-mail. Then, from the command line, specify the string you want to search for,
for example:


$ java GMapsAPISearch Grantham


The results are dumped out, including the structure of the information returned, which
includes data such as the URL, title, snippet, and size information.

Free download pdf