Wednesday, 18 January 2012

Saving map images in Android

Recently I've been working on a little Android project and wanted to save thumbnail images of a map within the application. This post is just sharing how to do exactly that. Nothing too complicated.

public class MyMapActivity extends MapActivity {
    private MapView mapView;

    ...

    private Bitmap getMapImage() {
        /* Position map for output */
        MapController mc = mapView.getController();
        mc.setCenter(SOME_POINT);
        mc.setZoom(16);

        /* Capture drawing cache as bitmap */
        mapView.setDrawingCacheEnabled(true);
        Bitmap bmp = Bitmap.createBitmap(mapView.getDrawingCache());
        mapView.setDrawingCacheEnabled(false);

        return bmp;
    }

    private void saveMapImage() {
        String filename = "foo.png";
        File f = new File(getExternalFilesDir(null), filename);
        FileOutputStream out = new FileOutputStream(f);
    
        Bitmap bmp = getMapImage();
    
        bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
    
        out.close();
    }
}

In the getMapImage method, we're telling the map controller to move to a particular point (this may not matter to you, you may just want to take the image as it appears) and zooming in to show a sufficient level of detail. Then a Bitmap is created from the map view's drawing cache. The saveMapImage method is just an example of how you may want to save an image to the application's external file directory.

5 comments:

  1. i'm trying to use your code but i need that getExternalFilesDir() methode which should return a File type (what file are you using)

    thank's in advance

    could you send me a response as soon as possible on my google account (it's kind of urgent)

    ReplyDelete
    Replies
    1. http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)

      Delete
    2. thank's for your help, you're a life saver

      Delete
  2. It is showing an null pointer exception!!

    ReplyDelete
    Replies
    1. The code above is fine, you'll have forgotten to initialize something elsewhere.

      Delete