色々遊んだけど特に問題なさそう…
(ズームレベルを変更したので、常に「青」だけになることはありませんでした)
public class TestGoogleMaps {
public static void main(String[] args) {
new TestGoogleMaps();
}
public TestGoogleMaps() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
final MapPane mapPane = new MapPane();
JButton random = new JButton("Random");
random.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String lat = Double.toString((Math.random() * 180) - 90);
String longt = Double.toString((Math.random() * 360) - 180);
new LoadMapTask((JButton)e.getSource(), mapPane, lat, longt).execute();
((JButton)e.getSource()).setEnabled(false);
}
});
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(mapPane);
frame.add(random, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MapPane extends JPanel {
private BufferedImage mapImage;
private String latitude;
private String longitude;
@Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
public void setMap(String lat, String log, BufferedImage image) {
mapImage = image;
latitude = lat;
longitude = log;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (mapImage != null) {
int x = (getWidth() - mapImage.getWidth()) / 2;
int y = (getHeight() - mapImage.getHeight()) / 2;
g.drawImage(mapImage, x, y, this);
FontMetrics fm = g.getFontMetrics();
g.drawString(latitude + "x" + longitude, 0, fm.getAscent());
}
}
}
public class LoadMapTask extends SwingWorker<BufferedImage, Object> {
private String latitude;
private String longitude;
private MapPane mapPane;
private JButton master;
public LoadMapTask(JButton master, MapPane mapPane, String latitude, String lonitude) {
this.mapPane = mapPane;
this.latitude = latitude;
this.longitude = lonitude;
this.master = master;
}
@Override
protected BufferedImage doInBackground() throws Exception {
BufferedImage mapImage = null;
try {
URL map = new URL("http://maps.google.com/staticmap?center=" + latitude + "," + longitude + "&zoom=5&size=500x500");
System.out.println(map);
mapImage = ImageIO.read(map);
} catch (Exception exp) {
exp.printStackTrace();
}
return mapImage;
}
@Override
protected void done() {
try {
mapPane.setMap(latitude, longitude, get());
} catch (InterruptedException | ExecutionException ex) {
ex.printStackTrace();
}
master.setEnabled(true);
}
}
}