Package org.geotools.mbtiles

Examples of org.geotools.mbtiles.MBTilesFile


    protected File sourceFile;
       
    public MBTilesReader(Object source, Hints hints) throws IOException {
        sourceFile = MBTilesFormat.getFileFromSource(source);

        MBTilesFile file = new MBTilesFile(sourceFile);

        metadata = file.loadMetaData();
       
        try {
            bounds = ReferencedEnvelope.create(metadata.getBounds(), WGS_84).transform(SPHERICAL_MERCATOR, true);
        } catch (Exception e) {
            bounds = null;
        }
        originalEnvelope = new GeneralEnvelope(bounds == null ? WORLD_ENVELOPE : bounds);

        long maxZoom;
        try {
            maxZoom = file.maxZoom();
        } catch (SQLException e) {
            throw new IOException(e);
        }

        long size = Math.round(Math.pow(ZOOM_LEVEL_BASE, maxZoom)) * DEFAULT_TILE_SIZE;
 
View Full Code Here


        return new MBTilesFormat();
    }
   
    @Override
    public GridCoverage2D read(GeneralParameterValue[] parameters) throws IllegalArgumentException, IOException {
        MBTilesFile file = new MBTilesFile(sourceFile);
       
        ReferencedEnvelope requestedEnvelope = null;
        Rectangle dim = null;
       
        if (parameters != null) {
            for (int i = 0; i < parameters.length; i++) {
                final ParameterValue param = (ParameterValue) parameters[i];
                final ReferenceIdentifier name = param.getDescriptor().getName();
                if (name.equals(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName())) {
                    final GridGeometry2D gg = (GridGeometry2D) param.getValue();
                    try {                       
                        requestedEnvelope = ReferencedEnvelope.create(gg.getEnvelope(), gg.getCoordinateReferenceSystem()).transform(SPHERICAL_MERCATOR, true);;
                    } catch (Exception e) {
                        requestedEnvelope = null;
                    }
                   
                    dim = gg.getGridRange2D().getBounds();
                    continue;
                }
            }
        }
       
        if (requestedEnvelope == null) {
            requestedEnvelope = bounds;
        }   
       
        long zoomLevel = 0;
        long leftTile, topTile, rightTile, bottomTile;
       
        if (requestedEnvelope != null && dim != null) {
            //find the closest zoom based on horizontal resolution
            double ratioWidth = requestedEnvelope.getSpan(0) / WORLD_ENVELOPE.getSpan(0); //proportion of total width that is being requested
            double propWidth = dim.getWidth() / ratioWidth; //this is the width in pixels that the whole world would have in the requested resolution
            zoomLevel = Math.round(Math.log(propWidth / DEFAULT_TILE_SIZE) / Math.log(ZOOM_LEVEL_BASE));
            //the closest zoom level to the resolution, based on the formula width = zoom_base^zoom_level * tile_size -> zoom_level = log(width / tile_size)/log(zoom_base)
        }
                               
        try { //now take a zoom level that is available in the database
            zoomLevel = file.closestZoom(zoomLevel);
        } catch (SQLException e1) {
            throw new IOException(e1);
        }       
       
        long numberOfTiles = Math.round(Math.pow(ZOOM_LEVEL_BASE, zoomLevel)); //number of tile columns/rows for chosen zoom level
        double resX = WORLD_ENVELOPE.getSpan(0) / numberOfTiles; //points per tile
        double resY = WORLD_ENVELOPE.getSpan(1) / numberOfTiles; //points per tile       
        double offsetX = WORLD_ENVELOPE.getMinimum(0);
        double offsetY = WORLD_ENVELOPE.getMinimum(1);     
       
        try { //take available tiles from database
            leftTile = file.minColumn(zoomLevel);
            rightTile = file.maxColumn(zoomLevel);
            bottomTile = file.minRow(zoomLevel);
            topTile = file.maxRow(zoomLevel);           
        } catch (SQLException e) {
            throw new IOException(e);
        }
       
        if (requestedEnvelope != null) { //crop tiles to requested envelope                  
            leftTile = Math.max(leftTile, Math.round(Math.floor((requestedEnvelope.getMinimum(0) - offsetX) / resX )));
            bottomTile = Math.max(bottomTile, Math.round(Math.floor((requestedEnvelope.getMinimum(1) - offsetY) / resY )));
            rightTile = Math.max(leftTile, Math.min(rightTile, Math.round(Math.floor((requestedEnvelope.getMaximum(0) - offsetX) / resX ))));
            topTile = Math.max(bottomTile, Math.min(topTile, Math.round(Math.floor((requestedEnvelope.getMaximum(1) - offsetY) / resY ))));           
        }
       
        int width = (int) (rightTile - leftTile + 1) * DEFAULT_TILE_SIZE;
        int height = (int) (topTile - bottomTile + 1) * DEFAULT_TILE_SIZE;
       
        //recalculate the envelope we are actually returning
        ReferencedEnvelope resultEnvelope = new ReferencedEnvelope(offsetX + leftTile * resX, offsetX + (rightTile+1) * resX, offsetY + bottomTile * resY, offsetY + (topTile+1) * resY, SPHERICAL_MERCATOR);
                       
        BufferedImage image = null;
       
        MBTilesFile.TileIterator it;
        try {
          it = file.tiles(zoomLevel, leftTile, bottomTile, rightTile, topTile);
        } catch (SQLException e) {
            throw new IOException(e);
        }

        while (it.hasNext()) {               
View Full Code Here

            new Envelope(-0.17578125, -0.087890625, 0.17578125, 0.087890625));
        mapContent.getRequest().getFormatOptions().put("min_zoom", "10");
        mapContent.getRequest().getFormatOptions().put("max_zoom", "11");
       
        WebMap map = format.produceMap(mapContent);
        MBTilesFile mbtiles = createMbTilesFiles(map);
       
        MBTilesMetadata metadata = mbtiles.loadMetaData();
       
        assertEquals("World_Lakes", metadata.getName());
        assertEquals("0", metadata.getVersion());
        assertEquals("World, null", metadata.getDescription());
        assertEquals(-0.17578125, metadata.getBounds().getMinimum(0), 0.001);
        assertEquals(-0.087890625, metadata.getBounds().getMaximum(0), 0.001);
        assertEquals(0.17578125, metadata.getBounds().getMaximum(1), 0.001);
        assertEquals(0.087890625, metadata.getBounds().getMinimum(1), 0.001);
        assertEquals(MBTilesMetadata.t_type.OVERLAY, metadata.getType());
        assertEquals(MBTilesMetadata.t_format.PNG, metadata.getFormat());
       
        assertEquals(1, mbtiles.numberOfTiles());

        MBTilesFile.TileIterator tiles = mbtiles.tiles();
        assertTrue(tiles.hasNext());
        MBTilesTile e = tiles.next();
        assertEquals(10, e.getZoomLevel());
        assertEquals(511, e.getTileColumn());
        assertEquals(512, e.getTileRow());
        assertNotNull(e.getData());
        tiles.close();
       
        mbtiles.close();
    }
View Full Code Here

            new Envelope(-0.17578125, -0.087890625, 0.17578125, 0.087890625));
        mapContent.getRequest().getFormatOptions().put("min_zoom", "10");
        mapContent.getRequest().getFormatOptions().put("max_zoom", "11");
        // Create a temporary file for the mbtiles
        File f = File.createTempFile("temp2", ".mbtiles", new File("target"));
        MBTilesFile mbtiles = new MBTilesFile(f);
        mbtiles.init();
        // Add tiles to the file(Internally uses the MBtilesFileWrapper)
        format.addTiles(mbtiles, mapContent.getRequest(), null);
        // Ensure everything is correct
        MBTilesMetadata metadata = mbtiles.loadMetaData();
       
        assertEquals("World_Lakes", metadata.getName());
        assertEquals("0", metadata.getVersion());
        assertEquals("World, null", metadata.getDescription());
        assertEquals(-0.17578125, metadata.getBounds().getMinimum(0), 0.001);
        assertEquals(-0.087890625, metadata.getBounds().getMaximum(0), 0.001);
        assertEquals(0.17578125, metadata.getBounds().getMaximum(1), 0.001);
        assertEquals(0.087890625, metadata.getBounds().getMinimum(1), 0.001);
        assertEquals(MBTilesMetadata.t_type.OVERLAY, metadata.getType());
        assertEquals(MBTilesMetadata.t_format.PNG, metadata.getFormat());
       
        assertEquals(1, mbtiles.numberOfTiles());

        MBTilesFile.TileIterator tiles = mbtiles.tiles();
        assertTrue(tiles.hasNext());
        MBTilesTile e = tiles.next();
        assertEquals(10, e.getZoomLevel());
        assertEquals(511, e.getTileColumn());
        assertEquals(512, e.getTileRow());
        assertNotNull(e.getData());
        tiles.close();
        // Closure of the files
        mbtiles.close();
        FileUtils.deleteQuietly(f);
    }
View Full Code Here

        FileOutputStream fout = new FileOutputStream(f);
        rawMap.writeTo(fout);
        fout.flush();
        fout.close();
       
        return new MBTilesFile(f);
    }
View Full Code Here

        File file = new File(path, "World.mbtiles");
        // File file = getDataDirectory().findFile("data", "test.mbtiles");
        assertNotNull(file);
        assertTrue(file.exists());

        MBTilesFile mbtiles = new MBTilesFile(file);
        MBTilesMetadata metadata = mbtiles.loadMetaData();
        assertEquals(11, mbtiles.maxZoom());
        assertEquals(10, mbtiles.minZoom());
        assertEquals("World", metadata.getName());

        assertEquals(-0.17578125, metadata.getBounds().getMinimum(0), 0.0001);
        assertEquals(-0.087890625, metadata.getBounds().getMinimum(1), 0.0001);
        assertEquals(0.17578125, metadata.getBounds().getMaximum(0), 0.0001);
        assertEquals(0.087890625, metadata.getBounds().getMaximum(1), 0.0001);

        try {
            mbtiles.close();
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
        }
    }
View Full Code Here

    private static class MbTilesFileWrapper implements TilesFile {

        MBTilesFile mbTiles;

        public MbTilesFileWrapper() throws IOException {
            mbTiles = new MBTilesFile();
            mbTiles.init();
        }
View Full Code Here

        } else {
            file = new File(createTempDir(storage.getStorage()), name + ".mbtiles");
        }

        // Create the MBTile file
        MBTilesFile mbtile = new MBTilesFile(file, true);
        try {
            // Initialize the MBTile file in order to avoid exceptions when accessing the geoPackage file
            mbtile.init();

            // Create the GetMap request to use
            GetMapRequest request = new GetMapRequest();

            // Create the layers map for the request
            ArrayList<MapLayerInfo> layers = new ArrayList<MapLayerInfo>();

            // Get the layers from the catalog
            for (String layername : layerz) {
                LayerInfo layerInfo = catalog.getLayerByName(layername);
                // Ensure the Layer is present
                if (layerInfo == null) {
                    throw new ServiceException("Layer not found: " + layername);
                }

                layers.add(new MapLayerInfo(layerInfo));
            }

            request.setLayers(layers);

            // Generate the bounding box if not present
            if (boundingbox == null) {
                try {

                    // generate one from requests layers

                    ReferencedEnvelope bbox = null;
                    for (MapLayerInfo l : request.getLayers()) {
                        ResourceInfo r = l.getResource();
                        // use native bbox
                        ReferencedEnvelope b = r.getNativeBoundingBox();
                        if (bbox != null) {
                            // transform
                            b = b.transform(bbox.getCoordinateReferenceSystem(), true);
                        }

                        if (bbox != null) {
                            bbox.include(b);
                        } else {
                            bbox = b;
                        }
                    }

                    request.setBbox(bbox);
                } catch (Exception e) {
                    String msg = "Must specify bbox, unable to derive from requested layers";
                    throw new RuntimeException(msg, e);
                }
            } else {
                request.setBbox(boundingbox);
            }

            // Extract CRS
            CoordinateReferenceSystem crs = boundingbox.getCoordinateReferenceSystem();

            // Set the request CRS
            if (crs == null) {
                // use crs of the layer
                ResourceInfo r = request.getLayers().iterator().next().getResource();
                crs = r.getCRS();
                request.setCrs(crs);
            } else {
                request.setCrs(crs);
            }

            // Set the request SRS
            request.setSRS(CRS.toSRS(crs));

            // Set Background color and Transparency
            if (bgColor != null && !bgColor.isEmpty()) {
                request.setBgColor(Color.decode(bgColor));
            }
            request.setTransparent(transparency == null ? false : transparency);

            // Add a style
            if (stylePath != null) {
                request.setStyleUrl(stylePath);
            } else if (styleBody != null && !styleBody.isEmpty()) {
                request.setStyleBody(styleBody);
            } else {
                request.setStyles(new ArrayList<Style>());
                if (styleNames != null && !styleNames.isEmpty()) {
                    for (String styleName : styleNames) {
                        StyleInfo info = catalog.getStyleByName(styleName);
                        if (info != null) {
                            request.getStyles().add(info.getStyle());
                        } else {
                            request.getStyles().add(null);
                        }
                    }
                }
                if (request.getStyles().isEmpty()) {
                    for (MapLayerInfo info : request.getLayers()) {
                        request.getStyles().add(info.getDefaultStyle());
                    }
                }
            }
            // Set the format of the mbtiles images
            request.setFormat("none");
            Map formatOptions = new HashMap();
            formatOptions.put("format", format);
            // Configure zoom levels if present
            if (minZoom != null) {
                formatOptions.put("min_zoom", minZoom);
            }
            if (maxZoom != null) {
                formatOptions.put("max_zoom", maxZoom);
            }
            if (minColumn != null) {
                formatOptions.put("min_column", minColumn);
            }
            if (maxColumn != null) {
                formatOptions.put("max_column", maxColumn);
            }
            if (minRow != null) {
                formatOptions.put("min_row", minRow);
            }
            if (maxRow != null) {
                formatOptions.put("max_row", maxRow);
            }
            // Set the gridSet name
            formatOptions.put(GRIDSET_NAME, EPSG_900913);
            // Add the format options to the request
            request.setFormatOptions(formatOptions);

            // Execute the requests
            mapOutput.addTiles(mbtile, request, name);
        } catch (Exception e) {
            if (LOGGER.isLoggable(Level.SEVERE)) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
            }
            throw new ProcessException(e);
        } finally {
            // Close the connection
            if (mbtile != null) {
                try {
                    mbtile.close();
                } catch (Exception e) {
                    if (LOGGER.isLoggable(Level.SEVERE)) {
                        LOGGER.log(Level.SEVERE, e.getMessage(), e);
                    }
                }
View Full Code Here

TOP

Related Classes of org.geotools.mbtiles.MBTilesFile

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.