Thursday, July 11, 2013

Java - Generate Image from Google Maps

Beside this API, Google Maps also provides an URL based API for extracting static Google Maps directly into desktop application, without requiring JavaScript or access keys. This API is very well explained here: http://code.google.com/apis/maps/documentation/staticmaps/index.html.

public class ImageUtils {
/**
* zoom level of the map, which determines the magnification level of the map.
* 0-21
*/
private static int zoom = 16;
/***
* scale:
* the number of pixels that are returned. scale=2 returns twice as many pixels as scale=1
*/
private static int scale = 2;
/***
* image size
* - free: 640x640
* - business: 2048x2048
*/
private static String size = "640x640";

/***
* maptype:
* roadmap, satellite, hybrid, and terrain.
*/
private static String maptype = "roadmap";

/***
* specifies whether the application requesting the static map is using a sensor to determine the user's location
*/
private static boolean sensor = false;

/***
* defines a marker of location.
* ie, color:blue, label:A
*/
private static String markers = "color:blue%7Clabel:A%7C";

public static void main(String[] args) throws IOException{
String imageFile = "d:\\plot.png";
String address = "Donaufelder straße 16, 1040 Wien, Österreich";
generateGoogleImage(address,imageFile);
}

private static File generateGoogleImage(String address,String imageFile){
address = address.replace(" ","+");
File googleImage = new File(imageFile);
try {
String addressGoogleUrl = "http://maps.googleapis.com/maps/api/staticmap?" +
    "center=" + address +
    "&zoom=" + zoom +
    "&size=" + size +
    "&scale=" + scale +
    "&maptype="+ maptype +
    "&markers=" + markers +
    address+
    "&sensor="+ sensor;

System.out.println("Address!"+"\t"+addressGoogleUrl);
   BufferedImage img = ImageIO.read(new URL(addressGoogleUrl));
   ImageIO.write(img, "png", googleImage);
   System.out.println("\n\t"+googleImage.getPath());
   } catch (Exception ex) {
        System.out.println("Error!" + ex);
   }
return googleImage;
}
}

Reference:
http://e-blog-java.blogspot.co.at/2011/12/display-static-google-maps-in-java.html

0 comments:

Post a Comment