Posted by cajo
on October 16, 2010 at 7:31 PM PDT
Google makes their extensive map collection available free of charge. Now it is seen in sites all over the web, but in this entry, I'll show you how simple it is to use in Java!
Google maps was a useful hit from the moment it went on line. Since then thousands of web pages have added map capability to their sites, courtesy of Google. Let me illustrate how you can add Google maps to your Java application.
Google furnishes its maps via a simple REST request. Does this mean you need to add some fancy REST framework to your application? Not at all! Java provides all you need right in the standard libraries, and it is very easy to do. (that's part of the real elegance of REST)
To request a map, you start with the following URL:
After the question mark, append all of the details you wish to be included in the map, separated by ampersand (&) symbols. For example:
This requests a road map centering on the Brooklyn Bridge, in New York City, at zoom level 14, 512x512 pixels in size. There's a very rich collection of options for specifying and decorating maps, Google has very helpfully made a highly detailed page explaining them all .
As I hope you've reasonably guessed; the http request dutifully returns an image of the map requested. That's all there is to it!
Happily, Java provides all the resources you need to use this great Google feature right in the Standard Edition. Simply create a java.net.URLConnection, request the content, and generate the map image. If you've not done this before, fear not, as Java makes it very easy to do, it looks a bit like this:
URLConnection con = new URL("http://maps...").openConnection();
InputStream is = con.getInputStream();
byte bytes = new byte[con.getContentLength()];
Toolkit tk = getToolkit();
map = tk.createImage(bytes);
tk.prepareImage(map, -1, -1, null);
The variable map now has the image, ready for presentation! Remarkably easy wasn't it? That's all it takes, and you can enjoy the full functionality of Google maps in any Java application.
Of course I'm not going to leave you hanging like that! ;-) I've written a complete free runnable GoogleMap Java component for you, it's less than one page of code. Try it out and let me know what you think.