Python mercantile.tile() Examples

The following are 30 code examples of mercantile.tile(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mercantile , or try the search function .
Example #1
Source File: burntiles.py    From supermercado with MIT License 6 votes vote down vote up
def tile_extrema(bounds, zoom):
    minimumTile = mercantile.tile(bounds[0], bounds[3], zoom)
    maximumTile = mercantile.tile(bounds[2], bounds[1], zoom)

    return {
        'x': {
            'min': minimumTile.x,
            'max': maximumTile.x + 1
            },
        'y': {
            'min': minimumTile.y,
            'max': maximumTile.y + 1
            }
        } 
Example #2
Source File: test_cli.py    From untiler with MIT License 6 votes vote down vote up
def add_tiles(self, zMin, zMax):
        zooms = np.arange(zMax - zMin + 2) + zMin - 1

        obj = {
            zMin - 1: [mercantile.tile(-122.4, 37.5, zMin - 1)]
        }

        basepath = '%s/jpg' % (self.path)
        if not os.path.isdir(basepath):
            os.mkdir(basepath)

        for i in range(1, len(zooms)):
            tiles = []
            os.mkdir("%s/%s" % (basepath, zooms[i]))
            for t in obj[zooms[i - 1]]:
                for tt in mercantile.children(t):
                    tiles.append(tt)
                    if os.path.isdir("%s/%s/%s" % (basepath, zooms[i], tt.x)):
                        shutil.copy(self.imgs[int(np.random.rand() + 0.1)],
                                    "%s/%s/%s/%s.jpg" % (basepath, zooms[i], tt.x, tt.y))
                    else:
                        os.mkdir("%s/%s/%s" % (basepath, zooms[i], tt.x))
                        shutil.copy(self.imgs[int(np.random.rand() + 0.1)],
                                    "%s/%s/%s/%s.jpg" % (basepath, zooms[i], tt.x, tt.y))
            obj[zooms[i]] = tiles 
Example #3
Source File: mbtiler.py    From rio-rgbify with MIT License 6 votes vote down vote up
def _tile_range(min_tile, max_tile):
    """
    Given a min and max tile, return an iterator of
    all combinations of this tile range

    Parameters
    -----------
    min_tile: list
        [x, y, z] of minimun tile
    max_tile:
        [x, y, z] of minimun tile

    Returns
    --------
    tiles: iterator
        iterator of [x, y, z] tiles
    """
    min_x, min_y, _ = min_tile
    max_x, max_y, _ = max_tile

    return itertools.product(range(min_x, max_x + 1), range(min_y, max_y + 1)) 
Example #4
Source File: test_cli.py    From untiler with MIT License 6 votes vote down vote up
def test_diff_zooms():
    with TestTiler() as testtiles:
        testtiles.add_tiles(15, 16)
        testtiles.add_tiles(17, 18)
        tmp = testtiles.path
        runner = CliRunner()

        runner.invoke(cli, ['streamdir', tmp, tmp, '-c', '15'])

        with rio.open(os.path.join(tmp, '15-5242-12697-tile.tif')) as src:
            assert src.shape == (2048, 2048)
            assert src.count == 4

        with rio.open(os.path.join(tmp, '15-5242-12696-tile.tif')) as src:
            assert src.shape == (512, 512)
            assert src.count == 4 
Example #5
Source File: __init__.py    From sharedstreets-python with MIT License 6 votes vote down vote up
def get_bbox(minlon, minlat, maxlon, maxlat, data_url_template=None):
    ''' Get a single Frames instance of SharedStreets entities in an area.
    '''
    bounds = (minlon, minlat, maxlon, maxlat)
    ul = mercantile.tile(minlon, maxlat, tile.DATA_ZOOM)
    lr = mercantile.tile(maxlon, minlat, tile.DATA_ZOOM)
    
    tiles = [
        tile.get_tile(tile.DATA_ZOOM, x, y, data_url_template) for (x, y)
        in itertools.product(range(ul.x, lr.x+1), range(ul.y, lr.y+1))
        ]
    
    all_geometries = functools.reduce(lambda d, t: dict(d, **t.geometries), tiles, {})
    all_intersections = functools.reduce(lambda d, t: dict(d, **t.intersections), tiles, {})

    return _make_frames(all_intersections.values(), all_geometries.values(), bounds) 
Example #6
Source File: conftest.py    From terracotta with MIT License 5 votes vote down vote up
def raster_file_xyz_lowzoom(raster_file):
    import rasterio
    import rasterio.warp
    import mercantile

    with rasterio.open(str(raster_file)) as src:
        raster_bounds = rasterio.warp.transform_bounds(src.crs, 'epsg:4326', *src.bounds)
    raster_center_x = (raster_bounds[0] + raster_bounds[2]) / 2
    raster_center_y = (raster_bounds[1] + raster_bounds[3]) / 2

    zoom = 10
    tile = mercantile.tile(raster_center_x, raster_center_y, zoom)
    return (tile.x, tile.y, zoom) 
Example #7
Source File: xyz.py    From terracotta with MIT License 5 votes vote down vote up
def get_tile_data(driver: Driver,
                  keys: Union[Sequence[str], Mapping[str, str]],
                  tile_xyz: Tuple[int, int, int] = None,
                  *, tile_size: Tuple[int, int] = (256, 256),
                  preserve_values: bool = False,
                  asynchronous: bool = False) -> Any:
    """Retrieve raster image from driver for given XYZ tile and keys"""

    if tile_xyz is None:
        # read whole dataset
        return driver.get_raster_tile(
            keys, tile_size=tile_size, preserve_values=preserve_values,
            asynchronous=asynchronous
        )

    # determine bounds for given tile
    metadata = driver.get_metadata(keys)
    wgs_bounds = metadata['bounds']

    tile_x, tile_y, tile_z = tile_xyz

    if not tile_exists(wgs_bounds, tile_x, tile_y, tile_z):
        raise exceptions.TileOutOfBoundsError(
            f'Tile {tile_z}/{tile_x}/{tile_y} is outside image bounds'
        )

    mercator_tile = mercantile.Tile(x=tile_x, y=tile_y, z=tile_z)
    target_bounds = mercantile.xy_bounds(mercator_tile)

    return driver.get_raster_tile(
        keys, tile_bounds=target_bounds, tile_size=tile_size,
        preserve_values=preserve_values, asynchronous=asynchronous
    ) 
Example #8
Source File: benchmarks.py    From terracotta with MIT License 5 votes vote down vote up
def get_xyz(raster_file, zoom):
    import rasterio
    import rasterio.warp
    import mercantile

    with rasterio.open(str(raster_file)) as src:
        raster_bounds = rasterio.warp.transform_bounds(src.crs, 'epsg:4326', *src.bounds)
    raster_center_x = (raster_bounds[0] + raster_bounds[2]) / 2
    raster_center_y = (raster_bounds[1] + raster_bounds[3]) / 2

    tile = mercantile.tile(raster_center_x, raster_center_y, zoom)
    return (tile.x, tile.y, zoom) 
Example #9
Source File: raster.py    From rio-glui with MIT License 5 votes vote down vote up
def tile_exists(self, z, x, y):
        """Check if a mercator tile is within raster bounds."""
        mintile = mercantile.tile(self.bounds[0], self.bounds[3], z)
        maxtile = mercantile.tile(self.bounds[2], self.bounds[1], z)
        return (
            (x <= maxtile.x + 1)
            and (x >= mintile.x)
            and (y <= maxtile.y + 1)
            and (y >= mintile.y)
        ) 
Example #10
Source File: raster.py    From rio-glui with MIT License 5 votes vote down vote up
def read_tile(self, z, x, y):
        """Read raster tile data and mask."""
        mercator_tile = mercantile.Tile(x=x, y=y, z=z)
        tile_bounds = mercantile.xy_bounds(mercator_tile)
        return tile_read(
            self.path,
            tile_bounds,
            self.tiles_size,
            indexes=self.indexes,
            nodata=self.nodata,
        ) 
Example #11
Source File: stac.py    From cogeo-mosaic with MIT License 5 votes vote down vote up
def tile(self, x: int, y: int, z: int) -> List[str]:
        """Retrieve assets for tile."""
        return get_assets_from_json(self.mosaic_def.tiles, self.quadkey_zoom, x, y, z) 
Example #12
Source File: stac.py    From cogeo-mosaic with MIT License 5 votes vote down vote up
def point(self, lng: float, lat: float) -> List[str]:
        """Retrieve assets for point."""
        tile = mercantile.tile(lng, lat, self.quadkey_zoom)
        return get_assets_from_json(
            self.mosaic_def.tiles, self.quadkey_zoom, tile.x, tile.y, tile.z
        ) 
Example #13
Source File: s3.py    From cogeo-mosaic with MIT License 5 votes vote down vote up
def tile(self, x: int, y: int, z: int) -> List[str]:
        """Retrieve assets for tile."""
        return get_assets_from_json(self.mosaic_def.tiles, self.quadkey_zoom, x, y, z) 
Example #14
Source File: s3.py    From cogeo-mosaic with MIT License 5 votes vote down vote up
def point(self, lng: float, lat: float) -> List[str]:
        """Retrieve assets for point."""
        tile = mercantile.tile(lng, lat, self.quadkey_zoom)
        return get_assets_from_json(
            self.mosaic_def.tiles, self.quadkey_zoom, tile.x, tile.y, tile.z
        ) 
Example #15
Source File: dynamodb.py    From cogeo-mosaic with MIT License 5 votes vote down vote up
def tile(self, x: int, y: int, z: int) -> List[str]:
        """Retrieve assets for tile."""
        return self.get_assets(x, y, z) 
Example #16
Source File: file.py    From cogeo-mosaic with MIT License 5 votes vote down vote up
def tile(self, x: int, y: int, z: int) -> List[str]:
        """Retrieve assets for tile."""
        return get_assets_from_json(self.mosaic_def.tiles, self.quadkey_zoom, x, y, z) 
Example #17
Source File: file.py    From cogeo-mosaic with MIT License 5 votes vote down vote up
def point(self, lng: float, lat: float) -> List[str]:
        """Retrieve assets for point."""
        tile = mercantile.tile(lng, lat, self.quadkey_zoom)
        return get_assets_from_json(
            self.mosaic_def.tiles, self.quadkey_zoom, tile.x, tile.y, tile.z
        ) 
Example #18
Source File: http.py    From cogeo-mosaic with MIT License 5 votes vote down vote up
def tile(self, x: int, y: int, z: int) -> List[str]:
        """Retrieve assets for tile."""
        return get_assets_from_json(self.mosaic_def.tiles, self.quadkey_zoom, x, y, z) 
Example #19
Source File: http.py    From cogeo-mosaic with MIT License 5 votes vote down vote up
def point(self, lng: float, lat: float) -> List[str]:
        """Retrieve assets for point."""
        tile = mercantile.tile(lng, lat, self.quadkey_zoom)
        return get_assets_from_json(
            self.mosaic_def.tiles, self.quadkey_zoom, tile.x, tile.y, tile.z
        ) 
Example #20
Source File: conftest.py    From terracotta with MIT License 5 votes vote down vote up
def raster_file_xyz(raster_file):
    import rasterio
    import rasterio.warp
    import mercantile

    with rasterio.open(str(raster_file)) as src:
        raster_bounds = rasterio.warp.transform_bounds(src.crs, 'epsg:4326', *src.bounds)
    raster_center_x = (raster_bounds[0] + raster_bounds[2]) / 2
    raster_center_y = (raster_bounds[1] + raster_bounds[3]) / 2

    zoom = 14
    tile = mercantile.tile(raster_center_x, raster_center_y, zoom)
    return (tile.x, tile.y, zoom) 
Example #21
Source File: xyz.py    From terracotta with MIT License 5 votes vote down vote up
def tile_exists(bounds: Sequence[float], tile_x: int, tile_y: int, tile_z: int) -> bool:
    """Check if an XYZ tile is inside the given physical bounds."""
    mintile = mercantile.tile(bounds[0], bounds[3], tile_z)
    maxtile = mercantile.tile(bounds[2], bounds[1], tile_z)

    return mintile.x <= tile_x <= maxtile.x and mintile.y <= tile_y <= maxtile.y 
Example #22
Source File: mbtiler.py    From rio-rgbify with MIT License 5 votes vote down vote up
def _make_tiles(bbox, src_crs, minz, maxz):
    """
    Given a bounding box, zoom range, and source crs,
    find all tiles that would intersect

    Parameters
    -----------
    bbox: list
        [w, s, e, n] bounds
    src_crs: str
        the source crs of the input bbox
    minz: int
        minumum zoom to find tiles for
    maxz: int
        maximum zoom to find tiles for

    Returns
    --------
    tiles: generator
        generator of [x, y, z] tiles that intersect
        the provided bounding box
    """
    w, s, e, n = transform_bounds(*[src_crs, "epsg:4326"] + bbox, densify_pts=0)

    EPSILON = 1.0e-10

    w += EPSILON
    s += EPSILON
    e -= EPSILON
    n -= EPSILON

    for z in range(minz, maxz + 1):
        for x, y in _tile_range(mercantile.tile(w, n, z), mercantile.tile(e, s, z)):
            yield [x, y, z] 
Example #23
Source File: mbtiler.py    From rio-rgbify with MIT License 5 votes vote down vote up
def _encode_as_png(data, profile, dst_transform):
    """
    Uses rasterio's virtual file system to encode a (3, 512, 512)
    array as a png-encoded bytearray.

    Parameters
    -----------
    data: ndarray
        (3 x 512 x 512) uint8 RGB array
    profile: dictionary
        dictionary of kwargs for png writing
    affine: Affine
        affine transform for output tile

    Returns
    --------
    contents: bytearray
        png-encoded bytearray of the provided input data
    """
    profile["affine"] = dst_transform

    with rasterio.open("/vsimem/tileimg", "w", **profile) as dst:
        dst.write(data)

    contents = bytearray(virtual_file_to_buffer("/vsimem/tileimg"))

    return contents 
Example #24
Source File: triangulate_raster.py    From make-surface with MIT License 5 votes vote down vote up
def triangulate(zoom, output, bounds, tile, tableid):
    if bounds:
        bounds = np.array(bounds).astype(np.float64)
    elif tile:
        epsilon = 1.0e-10
        tile = np.array(tile).astype(np.uint16)
        tBounds = mercantile.bounds(*tile)
        bounds = np.array([
            tBounds.west + epsilon,
            tBounds.south + epsilon,
            tBounds.east - epsilon,
            tBounds.north - epsilon
            ])
    else:
        sys.exit('Error: A bounds or tile must be specified')

    tileMin = mercantile.tile(bounds[0], bounds[3], zoom)
    tileMax = mercantile.tile(bounds[2], bounds[1], zoom)

    pGet = facetParent()

    if tableid:
        gJSON = createDBinit(tileMin, tileMax, zoom, pGet, tableid)
    else:
        gJSON = createFacets(tileMin, tileMax, zoom, pGet)

    if output:
        with open(output, 'w') as oFile:
            for feat in gJSON:
                oFile.write(json.dumps(feat) + '\n')
    else:
        for feat in gJSON:
            click.echo(json.dumps(feat)) 
Example #25
Source File: __init__.py    From sharedstreets-python with MIT License 5 votes vote down vote up
def get_tile(*args, **kwargs):
    ''' Get a single Frames instance for a tile of SharedStreets entities.
    
        All arguments are passed to tile.get_tile().
    '''
    logging.debug('get_tile', args, kwargs)
    T = tile.get_tile(*args, **kwargs)

    return _make_frames(T.intersections.values(), T.geometries.values()) 
Example #26
Source File: test_cli.py    From untiler with MIT License 5 votes vote down vote up
def test_cli_streamdir_mixed_ok():
    with TestTiler() as testtiles:
        testtiles.add_tiles(15, 16)
        testtiles.add_tiles(17, 18)
        tmp = testtiles.path
        runner = CliRunner()
        result = runner.invoke(cli, ['streamdir', tmp, tmp, '-c', '14'])
        assert result.output.rstrip() == os.path.join(tmp, '14-2621-6348-tile.tif')

        with rio.open(result.output.rstrip()) as src:
            assert src.shape == (4096, 4096)  # matches z18
            assert src.count == 4 
Example #27
Source File: test_cli.py    From untiler with MIT License 5 votes vote down vote up
def test_cli_streamdir_all_ok():
    with TestTiler() as testtiles:
        testtiles.add_tiles(15, 18)
        tmp = testtiles.path
        runner = CliRunner()
        result = runner.invoke(cli, ['streamdir', tmp, tmp, '-c', '14'])
        assert result.output.rstrip() == os.path.join(tmp, '14-2621-6348-tile.tif')
        with rio.open(result.output.rstrip()) as src:
            assert src.shape == (4096, 4096)  # matches z18
            assert src.count == 4 
Example #28
Source File: test_web.py    From rio-cogeo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_cog_translate_webZooms():
    """
    Test Web-Optimized COG.

    - Test COG size is a multiple of 256 (mercator tile size)
    - Test COG bounds are aligned with mercator grid at max zoom
    - Test high resolution internal tiles are equal to mercator tile using
      cogdumper and rio-tiler
    - Test overview internal tiles are equal to mercator tile using
      cogdumper and rio-tiler
    """

    runner = CliRunner()
    with runner.isolated_filesystem():
        web_profile = cog_profiles.get("raw")
        web_profile.update({"blockxsize": 256, "blockysize": 256})
        config = dict(GDAL_TIFF_OVR_BLOCKSIZE="128")

        cog_translate(
            raster_path_north,
            "cogeo.tif",
            web_profile,
            quiet=True,
            web_optimized=True,
            config=config,
        )
        with rasterio.open("cogeo.tif") as out_dst:
            assert get_max_zoom(out_dst) == 8

        cog_translate(
            raster_path_north,
            "cogeo.tif",
            web_profile,
            quiet=True,
            web_optimized=True,
            latitude_adjustment=False,
            config=config,
        )
        with rasterio.open("cogeo.tif") as out_dst:
            assert get_max_zoom(out_dst) == 10 
Example #29
Source File: tms_image.py    From gbdxtools with MIT License 5 votes vote down vote up
def _tile_coords(self, bounds):
        """ convert mercator bbox to tile index limits """
        tfm = pyproj.Transformer.from_crs(3857, 4326, always_xy=True)
        bounds = ops.transform(tfm.transform, box(*bounds)).bounds

        # because tiles have a common corner, the tiles that cover a
        # given tile includes the adjacent neighbors.
        # https://github.com/mapbox/mercantile/issues/84#issuecomment-413113791

        west, south, east, north = bounds
        epsilon = 1.0e-10
        if east != west and north != south:
            # 2D bbox
            # shrink the bounds a small amount so that
            # shapes/tiles round trip.
            west += epsilon
            south += epsilon
            east -= epsilon
            north -= epsilon

        params = [west, south, east, north, [self.zoom_level]]
        tile_coords = [(tile.x, tile.y) for tile in mercantile.tiles(*params)]
        xtiles, ytiles = zip(*tile_coords)
        minx = min(xtiles)
        miny = min(ytiles)
        maxx = max(xtiles) 
        maxy = max(ytiles)
        return minx, miny, maxx, maxy 
Example #30
Source File: tms_image.py    From gbdxtools with MIT License 5 votes vote down vote up
def shape(self):
        if self._bounds is None:
            _tile = mercantile.tile(180, -85.05, self.zoom_level)
            nx = _tile.x * self._tile_size
            ny = _tile.y * self._tile_size
            return tuple([self._nbands] + [ny, nx])
        else:
            return self._shape