Today is Saturday, 11th February 2017

Archive for May, 2015

How to Add Google Maps to Java Swing GUI

One of our readers recently had a question regarding Google Maps and Java Swing. He wanted to know how to use Google Maps inside of a Java Swing GUI application.

There are a number of solution out there. In fact, StackOverflow has a good thread about the various solutions.

There is also a commercial product that provides support for GoogleMaps. The JxBrowser component from teamdev.com is a Swing GUI component that you can add to your application. It provides tight integration with Google Maps and has the same look and feel of the regular GoogleMaps application. The only downside is the product costs money ($$$). You can visit the teamdev website to see sample source code and also get pricing information.

However, if you are looking for a free solution, then you can get basic GoogleMaps support. Note that this is very bare bones … but hey, it is free 🙂

Here’s a simple example that will display a GoogleMap in a Swing application.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GoogleMapsDemo {
public static void main(String[] args) throws IOException {
JFrame test = new JFrame("Google Maps");
try {
String latitude = "40.714728";
String longitude = "-73.998672";
String imageUrl = "https://maps.googleapis.com/maps/api/staticmap?center="
+ latitude
+ ","
+ longitude
+ "&zoom=11&size=612x612&scale=2&maptype=roadmap";
String destinationFile = "image.jpg";
// read the map image from Google
// then save it to a local file: image.jpg
//
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
// create a GUI component that loads the image: image.jpg
//
ImageIcon imageIcon = new ImageIcon((new ImageIcon("image.jpg"))
.getImage().getScaledInstance(630, 600,
java.awt.Image.SCALE_SMOOTH));
test.add(new JLabel(imageIcon));
// show the GUI window
test.setVisible(true);
test.pack();
}
}

 

And here’s the output of the program.

googlemaps-demo

 

Enjoy!

 

Share