Creates a tile from Google format X Y and zoom
430465
def from_google(cls, google_x, google_y, zoom):
        """"""
        max_tile = (2 ** zoom) - 1
        assert 0 <= google_x <= max_tile, 'Google X needs to be a value between 0 and (2^zoom) -1.'
        assert 0 <= google_y <= max_tile, 'Google Y needs to be a value between 0 and (2^zoom) -1.'
        return cls(tms_x=google_x, tms_y=(2 ** zoom - 1) - google_y, zoom=zoom)
548296
def tileAddress(self, zoom, point):
        ""
        [x, y] = point
        assert x <= self.MAXX and x >= self.MINX
        assert y <= self.MAXY and y >= self.MINY
        assert zoom in range(0, len(self.RESOLUTIONS))

        tileS = self.tileSize(zoom)
        offsetX = abs(x - self.MINX)
        if self.originCorner == 'bottom-left':
            offsetY = abs(y - self.MINY)
        elif self.originCorner == 'top-left':
            offsetY = abs(self.MAXY - y)
        col = offsetX / tileS
        row = offsetY / tileS
        # We are exactly on the edge of a tile and the extent
        if x in (self.MINX, self.MAXX) and col.is_integer():
            col = max(0, col - 1)
        if y in (self.MINY, self.MAXY) and row.is_integer():
            row = max(0, row - 1)
        return [
            int(math.floor(col)),
            int(math.floor(row))
        ]
295298
def grid_tiles(self, bbox, zoomlevel):
        
        tiles = self.tileslist(bbox, [zoomlevel])
        grid = {}
        for (z, x, y) in tiles:
            if not grid.get(y):
                grid[y] = []
            grid[y].append(x)
        sortedgrid = []
        for y in sorted(grid.keys(), reverse=self.tile_scheme == 'tms'):
            sortedgrid.append([(x, y) for x in sorted(grid[y])])
        return sortedgrid
515293
function(bounds, zoomChanged, dragging) {
        OpenLayers.Layer.prototype.moveTo.apply(this, arguments);

        var firstRendering = (this.tile == null);

        if(zoomChanged || firstRendering) {

            //determine new tile size
            this.setTileSize();

            //determine new position (upper left corner of new bounds)
            var ulPx = this.map.getLayerPxFromLonLat({
                lon: this.extent.left,
                lat: this.extent.top
            });

            if(firstRendering) {
                //create the new tile
                this.tile = new OpenLayers.Tile.Image(this, ulPx, this.extent, 
                                                      null, this.tileSize);
                this.addTileMonitoringHooks(this.tile);
            } else {
                //just resize the tile and set it's new position
                this.tile.size = this.tileSize.clone();
                this.tile.position = ulPx.clone();
            }
            this.tile.draw();
        }
    }
1294784
@Override
    public Tile getTile(int x, int y, int zoom)
    {
        return new Tile(x, y, zoom)
        {
            @Override
            public synchronized boolean isLoaded()
            {
                return true;
            }

            @Override
            public BufferedImage getImage()
            {
                return emptyTile;
            }

        };
    }
1228783
public BufferedImage drawTileQueryAll(int x, int y, int zoom) {

		BoundingBox boundingBox = TileBoundingBoxUtils
				.getWebMercatorBoundingBox(x, y, zoom);

		BufferedImage image = null;

		// Query for all features
		FeatureResultSet resultSet = featureDao.queryForAll();

		try {

			int totalCount = resultSet.getCount();

			// Draw if at least one geometry exists
			if (totalCount > 0) {

				if (maxFeaturesPerTile == null
						|| totalCount <= maxFeaturesPerTile) {

					// Draw the tile image
					image = drawTile(zoom, boundingBox, resultSet);

				} else if (maxFeaturesTileDraw != null) {

					// Draw the unindexed max features tile
					image = maxFeaturesTileDraw.drawUnindexedTile(tileWidth,
							tileHeight, totalCount, resultSet);
				}

			}
		} finally {
			resultSet.close();
		}

		return image;
	}
686893
def tile(self, z, x, y):
        
        logger.debug(_("Download tile %s") % ((z, x, y),))
        # Render each keyword in URL ({s}, {x}, {y}, {z}, {size} ... )
        size = self.tilesize
        s = self.tiles_subdomains[(x + y) % len(self.tiles_subdomains)];
        try:
            url = self.tiles_url.format(**locals())
        except KeyError as e:
            raise DownloadError(_("Unknown keyword %s in URL") % e)

        logger.debug(_("Retrieve tile at %s") % url)
        r = DOWNLOAD_RETRIES
        sleeptime = 1
        while r > 0:
            try:
                request = requests.get(url, headers=self.headers)
                if request.status_code == 200:
                    return request.content
                raise DownloadError(_("Status code : %s, url : %s") % (request.status_code, url))
            except requests.exceptions.ConnectionError as e:
                logger.debug(_("Download error, retry (%s left). (%s)") % (r, e))
                r -= 1
                time.sleep(sleeptime)
                # progressivly sleep longer to wait for this tile
                if (sleeptime <= 10) and (r % 2 == 0):
                    sleeptime += 1  # increase wait
        raise DownloadError(_("Cannot download URL %s") % url)
1158243
def tile_at(self, zoom, position):
        
        x, y = self.project_pixels(position, zoom)
        return (zoom, int(x/self.tilesize), int(y/self.tilesize))
1043052
def for_pixels(cls, pixel_x, pixel_y, zoom):
        """"""
        tms_x = int(math.ceil(pixel_x / float(TILE_SIZE)) - 1)
        tms_y = int(math.ceil(pixel_y / float(TILE_SIZE)) - 1)
        return cls(tms_x=tms_x, tms_y=(2 ** zoom - 1) - tms_y, zoom=zoom)
1108288
def from_pixel(cls, pixel_x=0, pixel_y=0, zoom=None):
        """"""
        max_pixel = (2 ** zoom) * TILE_SIZE
        assert 0 <= pixel_x <= max_pixel, 'Point X needs to be a value between 0 and (2^zoom) * 256.'
        assert 0 <= pixel_y <= max_pixel, 'Point Y needs to be a value between 0 and (2^zoom) * 256.'
        meter_x = pixel_x * resolution(zoom) - ORIGIN_SHIFT
        meter_y = pixel_y * resolution(zoom) - ORIGIN_SHIFT
        meter_x, meter_y = cls._sign_meters(meters=(meter_x, meter_y), pixels=(pixel_x, pixel_y), zoom=zoom)
        return cls.from_meters(meter_x=meter_x, meter_y=meter_y)
1361738
public Coordinate tileTopLeft(int tx, int ty, int zoomLevel) {
        int px = tx * tileSize;
        int py = ty * tileSize;
        Coordinate result = pixelsToMeters(px, py, zoomLevel);
        return result;
    }
1364058
def extract_metatile(io, fmt, offset=None):
    

    ext = fmt.extension
    if offset is None:
        tile_name = '0/0/0.%s' % ext
    else:
        tile_name = '%d/%d/%d.%s' % (offset.zoom, offset.column, offset.row,
                                     ext)

    with zipfile.ZipFile(io, mode='r') as zf:
        if tile_name in zf.namelist():
            return zf.read(tile_name)
        else:
            return None
883966
def createTileUrl(self, x, y, z):
        '''
        
        '''
        return self.tileTemplate.replace('{{x}}', str(x)).replace('{{y}}', str(
            y)).replace('{{z}}', str(z))
463616
private static int writeGeoPackageFormatTiles(TileDao tileDao,
			File directory, String imageFormat, Integer width, Integer height,
			boolean rawImage) throws IOException {

		int tileCount = 0;

		// Go through each zoom level
		for (long zoomLevel = tileDao.getMinZoom(); zoomLevel <= tileDao
				.getMaxZoom(); zoomLevel++) {

			// Get the tile matrix at this zoom level
			TileMatrix tileMatrix = tileDao.getTileMatrix(zoomLevel);

			LOGGER.log(
					Level.INFO,
					"Zoom Level: "
							+ zoomLevel
							+ ", Width: "
							+ tileMatrix.getMatrixWidth()
							+ ", Height: "
							+ tileMatrix.getMatrixHeight()
							+ ", Max Tiles: "
							+ (tileMatrix.getMatrixWidth() * tileMatrix
									.getMatrixHeight()));

			File zDirectory = new File(directory, String.valueOf(zoomLevel));

			int zoomCount = 0;

			// Query for all tiles at the zoom level
			TileResultSet tileResultSet = tileDao.queryForTile(zoomLevel);

			while (tileResultSet.moveToNext()) {

				TileRow tileRow = tileResultSet.getRow();

				if (tileRow != null) {

					// Get the image bytes
					byte[] tileData = tileRow.getTileData();

					if (tileData != null) {

						// Make any needed directories for the image
						File xDirectory = new File(zDirectory,
								String.valueOf(tileRow.getTileColumn()));
						xDirectory.mkdirs();

						File imageFile = new File(xDirectory,
								String.valueOf(tileRow.getTileRow()) + "."
										+ imageFormat);

						if (rawImage) {

							// Write the raw image bytes to the file
							FileOutputStream fos = new FileOutputStream(
									imageFile);
							fos.write(tileData);
							fos.close();

						} else {

							// Read the tile image
							BufferedImage tileImage = tileRow
									.getTileDataImage();

							int tileWidth = width != null ? width : tileImage
									.getWidth();
							int tileHeight = height != null ? height
									: tileImage.getHeight();

							Image drawImage = null;
							if (tileImage.getWidth() != tileWidth
									|| tileImage.getHeight() != tileHeight) {
								drawImage = tileImage.getScaledInstance(
										tileWidth, tileHeight,
										Image.SCALE_SMOOTH);
							} else {
								drawImage = tileImage;
							}

							// Create the new image in the image format
							BufferedImage image = ImageUtils
									.createBufferedImage(tileWidth, tileHeight,
											imageFormat);
							Graphics graphics = image.getGraphics();

							// Draw the image
							graphics.drawImage(drawImage, 0, 0, null);

							// Write the image to the file
							ImageIO.write(image, imageFormat, imageFile);
						}

						zoomCount++;

						if (zoomCount % ZOOM_PROGRESS_FREQUENCY == 0) {
							LOGGER.log(Level.INFO, "Zoom " + zoomLevel
									+ " Tile Progress... " + zoomCount);
						}
					}
				}
			}
			tileResultSet.close();

			LOGGER.log(Level.INFO, "Zoom " + zoomLevel + " Tiles: " + zoomCount);

			tileCount += zoomCount;

		}
		return tileCount;
	}
246652
def tiles_from_geom(self, geometry, zoom):
        
        validate_zoom(zoom)
        if geometry.is_empty:
            return
        if not geometry.is_valid:
            raise ValueError("no valid geometry: %s" % geometry.type)
        if geometry.geom_type == "Point":
            yield self.tile_from_xy(geometry.x, geometry.y, zoom)
        elif geometry.geom_type == "MultiPoint":
            for point in geometry:
                yield self.tile_from_xy(point.x, point.y, zoom)
        elif geometry.geom_type in (
            "LineString", "MultiLineString", "Polygon", "MultiPolygon",
            "GeometryCollection"
        ):
            prepared_geometry = prep(clip_geometry_to_srs_bounds(geometry, self))
            for tile in self.tiles_from_bbox(geometry, zoom):
                if prepared_geometry.intersects(tile.bbox()):
                    yield tile
338035
def grid(metadata, layout, params):
  
  x = layout["x"]
  y = layout["y"]
  x_min = np.min(x)
  x_max = np.max(x)
  y_min = np.min(y)
  y_max = np.max(y)

  # this creates the grid
  bins = np.linspace(x_min, x_max, params["n_layer"] - 1)
  xd = np.digitize(x, bins)
  bins = np.linspace(y_min, y_max, params["n_layer"] - 1)
  yd = np.digitize(y, bins)

  # the number of tiles is the number of cells divided by the number of cells in each tile
  num_tiles = int(params["n_layer"]/params["n_tile"])
  print("num tiles", num_tiles)
  # we will save the tiles in an array indexed by the tile coordinates
  tiles = {}
  for ti in range(num_tiles):
    for tj in range(num_tiles):
      tiles[(ti,tj)] = {
        "x": [],
        "y": [],
        "ci": [], # cell-space x coordinate
        "cj": [], # cell-space y coordinate
        "gi": [], # global index
      }

  for i,xi in enumerate(x):
    if(i % 1000 == 0 or i+1 == len(x)):
      print("point", i+1, "/", len(x), end="\r")
    # layout-space coordinates
    yi = y[i]
    # grid-space cell coordinates
    ci = xd[i]
    cj = yd[i]
    # tile coordinate
    ti = math.floor(ci / params["n_tile"])
    tj = math.floor(cj / params["n_tile"])

    # TODO: don't append a point if it doesn't match a filter function provided in params
    filter = params.get("filter", lambda i,metadata: True)
    if(filter(i, metadata=metadata)):
      tiles[(ti,tj)]["x"].append(xi)
      tiles[(ti,tj)]["y"].append(yi)
      tiles[(ti,tj)]["ci"].append(ci)
      tiles[(ti,tj)]["cj"].append(cj)
      tiles[(ti,tj)]["gi"].append(i)
    
  return tiles
272181
def bbox(ctx, tile):
    """"""
    geom = TilePyramid(
        ctx.obj['grid'],
        tile_size=ctx.obj['tile_size'],
        metatiling=ctx.obj['metatiling']
    ).tile(*tile).bbox(pixelbuffer=ctx.obj['pixelbuffer'])
    if ctx.obj['output_format'] in ['WKT', 'Tile']:
        click.echo(geom)
    elif ctx.obj['output_format'] == 'GeoJSON':
        click.echo(geojson.dumps(geom))