高德地圖加載本地瓦片圖層LocalTileProvider
概述:
TileOverlay是栅格圖層的相關類。栅格圖層是顯示在基本地圖上的一組圖像。這些栅格可以是透明的,允許您增加一些新的功能到現有的地圖上。栅格圖層具有以下屬性:
-
栅格提供者:
提供者提供在栅格圖層上使用的圖像。您必須在栅格添加到地圖上之前指定提供者。一旦栅格添加到地圖之後,提供者将不能更改。如果栅格提供者發生變化,您必須使用cleartilecache()方法確定以前的栅格圖不再出現。
-
Z軸值:
Z軸是控制栅格圖層重複區域的繪制順序的值。Z軸較大的栅格圖層會在繪制在Z軸較小的栅格圖層上面。如果兩個栅格圖層的Z軸數值相同,則覆寫情況将随機出現。
-
可見性:
栅格圖層是否可見,隻是表示是否畫在地圖上。設定不可見的栅格圖層,将不被畫在地圖上,但會保留它的其他屬性。預設栅格圖層是可見的。
調用這個類的方法必須在主線程使用,操作失敗将會抛出IllegalStateException異常。
方法:
void
清空栅格圖層的緩存。 | |
| |
| 擷取栅格圖層的id。 |
| 傳回栅格圖層的Z軸值。 |
| |
| 傳回栅格圖層是否可見。 |
| 從地圖上删除栅格圖層。 |
| 設定栅格圖層可見屬性。 |
| 設定栅格圖層的Z軸值。 |
import com.amap.api.maps2d.model.Tile;
import com.amap.api.maps2d.model.TileProvider;
public class LocalTileTileProvider implements TileProvider {
private static final int TILE_WIDTH = 256;
private static final int TILE_HEIGHT = 256;
public static final int BUFFER_SIZE = 16 * 1024;
private String tilePath;
private byte[] tile;
public LocalTileTileProvider(String path) {
tilePath=path;
}
@Override
public final 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) {
InputStream in = null;
ByteArrayOutputStream buffer = null;
File f = new File(getTileFilename(x, y, zoom));
if(f.exists()){
try {
buffer = new ByteArrayOutputStream();
in = new FileInputStream(f);
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) {}
}
}else{
return null;
}
}
private String getTileFilename(int x, int y, int zoom) {
return tilePath + zoom + '/' +'x'+ x + 'y' + y + ".png";
}
@Override
public int getTileHeight() {
return TILE_HEIGHT;
}
@Override
public int getTileWidth() {
return TILE_WIDTH;
}
}
//調用地方
TileProvider tileProvider = new LocalTileProvider ( Environment . getExternalStorageDirectory ( ) + "/tile/32/" ) ; tileOverlay = aMap . addTileOverlay ( new TileOverlayOptions ( ) . tileProvider ( tileProvider ) ) ;