Android谷歌地图:如何使用TileProvider与资产文件夹中的图像

时间:2016-01-12 20:22:12

标签: android google-maps

我在下面编写了代码,使用Android Assets文件夹的完整路径。但是瓷砖提供商无法找到图像,因此地图保持为空而不显示任何图块。 如果有人可以协助解决这个问题吗?

Stream

1 个答案:

答案 0 :(得分:-1)

试试这个:

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    private TileOverlay mTiles;
    private AppCompatActivity mThis;
    private String MAP_URL_FORMAT = "%d/x%d_y%d.png";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mThis = this;
        setContentView(R.layout.tile_overlay);

        SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap map) {
        map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        LatLng supperland = new LatLng(31.978574, 34.744219);
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(supperland, 9));

        TileProvider tileProvider = new TileProvider() {

            int width = 256; //width;
            int height = 256; //height;

            @Override
            public Tile getTile(int x, int y, int zoom) {
                String path = String.format(Locale.US, MAP_URL_FORMAT, zoom, x, y);

                if(path == null) {
                    return NO_TILE;
                } else {
                    Tile tile;
                    try {
                        InputStream is = mThis.getAssets().open(path);
                        tile = new Tile(width, height, streamToBytes(is));
                    } catch (IOException var7) {
                        tile = null;
                    }

                    return tile;
                }
            }

            private byte[] streamToBytes(InputStream inputStream) throws IOException {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                read(inputStream, byteArrayOutputStream);
                return byteArrayOutputStream.toByteArray();
            }

            private long read(InputStream inputStream, OutputStream outputStream) throws IOException {
                byte[] var2 = new byte[4096];
                long var3 = 0L;

                while(true) {
                    int var5 = inputStream.read(var2);
                    if(var5 == -1) {
                        return var3;
                    }

                    outputStream.write(var2, 0, var5);
                    var3 += (long)var5;
                }
            }
        };

        mTiles = map.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
    }
}