Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Google Maps V2 - Sd card as Tile Provider

I'm developing an android app using Google Maps API V2 and i have to use offline tiles, i have all tiles (from open street maps in png format) of my entire city in my SD Card. I already tried to use TileProvider Interface but didn't work. How can i do that ? Thanks in advance.

like image 364
Guilherme Ruiz Avatar asked Sep 09 '13 19:09

Guilherme Ruiz


1 Answers

I modified somethings and it worked. Here is the code:

CustomMapTileProvider.java

public class CustomMapTileProvider implements TileProvider {
    private static final int TILE_WIDTH = 256;
    private static final int TILE_HEIGHT = 256;
    private static final int BUFFER_SIZE = 16 * 1024;

    Override
    public Tile getTile(int x, int y, int zoom) {
        byte[] image = readTileImage(x, y, zoom);
        return image == null ? null : new Tile(TILE_WIDTH, TILE_HEIGHT, image);
    }

    private byte[] readTileImage(int x, int y, int zoom) {
        FileInputStream in = null;
        ByteArrayOutputStream buffer = null;

        try { in = new FileInputStream(getTileFile(x, y, zoom));
            buffer = new ByteArrayOutputStream();
            int nRead;
            byte[] data = new byte[BUFFER_SIZE];

            while ((nRead = in .read(data, 0, BUFFER_SIZE)) != -1) {
                buffer.write(data, 0, nRead);
            }
            buffer.flush();
            return buffer.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            return null;
        } finally {
            if ( in != null)
                try { in .close();
                } catch (Exception ignored) {}
            if (buffer != null)
                try {
                    buffer.close();
                } catch (Exception ignored) {}
        }
    }

    private File getTileFile(int x, int y, int zoom) {
        File sdcard = Environment.getExternalStorageDirectory();
        String tileFile = "/TILES_FOLDER/" + zoom + '/' + x + '/' + y + ".png";
        File file = new File(sdcard, tileFile);
        return file;
    }
}

Add TileOverlay to your GoogleMap instance

...

map.setMapType(GoogleMap.MAP_TYPE_NONE);
TileOverlayOptions tileOverlay = new TileOverlayOptions();
tileOverlay.tileProvider(new CustomMapTileProvider());
map.addTileOverlay(tileOverlay).setZIndex(0);

...
like image 197
Guilherme Ruiz Avatar answered Sep 28 '22 17:09

Guilherme Ruiz