import java.io.*; import java.net.*; /** * From http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html * * @author Wayne Smith * */ public class Geocoder { /** * @param args * @exception MalformedURLException, IOException * * (If done properly, these exceptions would be handled with a try/catch) * * This is a demonstration of the application which accepts address searches * on Google Maps, and returns a point. What it really returns is a latitude * and longitude, which via some javascript, is loaded into your browser. * * However, instead of loading it into a browser, we are just going to have * it return the latitude and longitude only (no extra info/code), and * store that information in our Contact database. */ public static void main(String[] args) throws MalformedURLException, IOException { /** * Our search request: note the formatting: * * 1. http://maps.google.com/maps/geo (the location of geocoder) * 2. ?q= (begins the query) * 3. 1600+Amphitheatre+Parkway,+Mountain+View,+CA (the street, city, state * address of our request--I just split it up over two lines) * 4. &output (specifies format; csv) * 5. &oe=utf (sets encoding) * 6. &sensor=false (whether or not our device has GPS) * * All of these options are listed as required on the Google API site * (http://code.google.com/apis/maps/documentation/geocoding/index.html) * * Well, actually oe is optional but "strongly encouraged", and the api key * is supposedly required, but I didn't use it. */ String request = "http://maps.google.com/maps/geo?q=1600" + "+Amphitheatre+Parkway,+Mountain+View,+CA&output=csv&oe=utf8&sensor=false"; //create URL connection and set for output URL url = new URL(request); URLConnection connection = url.openConnection(); //Create response stream to read BufferedReader in = new BufferedReader( new InputStreamReader( connection.getInputStream())); //holds the response String response; String[] a; /** * read the response, just like file I/O * * currently we just print out, but to complete the project, * we would have to store this information. */ while ((response = in.readLine()) != null) { a = response.split(","); System.out.println(a[2] + ", " + a[3]); //debugging } in.close(); /** * Note on our output: * * Four fields are sent back, separated by three commas * * Field 1: The Status code, HTTP-stylish. 200 is all ok. * Field 2: The accuracy measurement. Range is guessed to be 1-10. * Results supposed to be ordered best-->worst. * Field 3: Lat * Field 4: Long */ } }