Converts TMS tile coordinates to QuadTree

@param pMapTileIndex
The tile coordinates to convert
@return The QuadTree as String.
778930
protected String quadTree(final long pMapTileIndex) {
		final StringBuilder quadKey = new StringBuilder();
		for (int i = MapTileIndex.getZoom(pMapTileIndex); i > 0; i--) {
			int digit = 0;
			final int mask = 1 << (i - 1);
			if ((MapTileIndex.getX(pMapTileIndex) & mask) != 0)
				digit += 1;
			if ((MapTileIndex.getY(pMapTileIndex) & mask) != 0)
				digit += 2;
			quadKey.append("" + digit);
		}

		return quadKey.toString();
	}
939744
function tileToGeoJSON(tile) {
    var bbox = tileToBBOX(tile);
    var poly = {
        type: 'Polygon',
        coordinates: [[
            [bbox[0], bbox[1]],
            [bbox[0], bbox[3]],
            [bbox[2], bbox[3]],
            [bbox[2], bbox[1]],
            [bbox[0], bbox[1]]
        ]]
    };
    return poly;
}
678352
public Rectangle getPositionRelativeToTile(Tile tile) {
        Point upperLeft = MercatorProjection.getPixelRelativeToTile(new LatLong(this.maxLatitude, minLongitude), tile);
        Point lowerRight = MercatorProjection.getPixelRelativeToTile(new LatLong(this.minLatitude, maxLongitude), tile);
        return new Rectangle(upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y);
    }
189053
public static Point QuadKeyToTileXY(final String quadKey, final Point reuse) {
		final Point out = reuse == null ? new Point() : reuse;
		if (quadKey == null || quadKey.length() == 0) {
			throw new IllegalArgumentException("Invalid QuadKey: " + quadKey);
		}
		int tileX = 0;
		int tileY = 0;
		final int zoom = quadKey.length();
		for (int i = 0 ; i < zoom;  i++) {
			final int value = 1 << i;
			switch (quadKey.charAt(zoom - i - 1)) {
				case '0':
					break;
				case '1':
					tileX += value;
					break;
				case '2':
					tileY += value;
					break;
				case '3':
					tileX += value;
					tileY += value;
					break;
				default:
					throw new IllegalArgumentException("Invalid QuadKey: " + quadKey);
			}
		}
		out.x = tileX;
		out.y = tileY;
		return out;
	}
1057001
public static TileGrid getTileGridFromWGS84(Point point, int zoom) {
		Projection projection = ProjectionFactory
				.getProjection(ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM);
		return getTileGrid(point, zoom, projection);
	}
1067645
public static int[] metersToTile( double mx, double my, int zoom, int tileSize ) {
        int[] p = metersToPixels(mx, my, zoom, tileSize);
        return pixelsToTile(p[0], p[1], tileSize);
    }
250442
public Drawable downloadTile(final long pMapTileIndex, final int redirectCount, final String targetUrl,
                                 final IFilesystemCache pFilesystemCache, final OnlineTileSourceBase pTileSource) throws CantContinueException {

        //prevent infinite looping of redirects, rare but very possible for misconfigured servers
        if (redirectCount>3) {
            return null;
        }

        String userAgent = null;
        if (pTileSource.getTileSourcePolicy().normalizesUserAgent()) {
            userAgent = Configuration.getInstance().getNormalizedUserAgent();
        }
        if (userAgent == null) {
            userAgent = Configuration.getInstance().getUserAgentValue();
        }
        if (!pTileSource.getTileSourcePolicy().acceptsUserAgent(userAgent)) {
            Log.e(IMapView.LOGTAG,"Please configure a relevant user agent; current value is: " + userAgent);
            return null;
        }
        InputStream in = null;
        OutputStream out = null;
        HttpURLConnection c=null;
        ByteArrayInputStream byteStream = null;
        ByteArrayOutputStream dataStream = null;
        try {
            final String tileURLString = targetUrl;

            if (Configuration.getInstance().isDebugMode()) {
                Log.d(IMapView.LOGTAG,"Downloading Maptile from url: " + tileURLString);
            }

            if (TextUtils.isEmpty(tileURLString)) {
                return null;
            }

            //TODO in the future, it may be necessary to allow app's using this library to override the SSL socket factory. It would here somewhere
            if (Configuration.getInstance().getHttpProxy() != null) {
                c = (HttpURLConnection) new URL(tileURLString).openConnection(Configuration.getInstance().getHttpProxy());
            } else {
                c = (HttpURLConnection) new URL(tileURLString).openConnection();
            }
            c.setUseCaches(true);
            c.setRequestProperty(Configuration.getInstance().getUserAgentHttpHeader(), userAgent);
            for (final Map.Entry<String, String> entry : Configuration.getInstance().getAdditionalHttpRequestProperties().entrySet()) {
                c.setRequestProperty(entry.getKey(), entry.getValue());
            }
            c.connect();


            // Check to see if we got success

            if (c.getResponseCode() != 200) {


                switch (c.getResponseCode()) {
                    case 301:
                    case 302:
                    case 307:
                    case 308:
                        if (Configuration.getInstance().isMapTileDownloaderFollowRedirects()) {
                            //this is a redirect, check the header for a 'Location' header
                            String redirectUrl = c.getHeaderField("Location");
                            if (redirectUrl != null) {
                                if (redirectUrl.startsWith("/")) {
                                    //in this case we need to stitch together a full url
                                    URL old = new URL(targetUrl);
                                    int port = old.getPort();
                                    boolean secure = targetUrl.toLowerCase().startsWith("https://");
                                    if (port == -1)
                                        if (targetUrl.toLowerCase().startsWith("http://")) {
                                            port = 80;
                                        } else {
                                            port = 443;
                                        }

                                    redirectUrl = (secure ? "https://" : "http") + old.getHost() + ":" + port + redirectUrl;
                                }
                                Log.i(IMapView.LOGTAG, "Http redirect for MapTile: " + MapTileIndex.toString(pMapTileIndex) + " HTTP response: " + c.getResponseMessage() + " to url " + redirectUrl);
                                return downloadTile(pMapTileIndex, redirectCount + 1, redirectUrl, pFilesystemCache, pTileSource);
                            }
                            break;
                        }	//else follow through the normal path of aborting the download
                    default: {
                        Log.w(IMapView.LOGTAG, "Problem downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " HTTP response: " + c.getResponseMessage());
                        if (Configuration.getInstance().isDebugMapTileDownloader()) {
                            Log.d(IMapView.LOGTAG, tileURLString);
                        }
                        Counters.tileDownloadErrors++;
                        in = c.getErrorStream(); // in order to have the error stream purged by the finally block
                        return null;
                    }
                }



            }
            String mime = c.getHeaderField("Content-Type");
            if (Configuration.getInstance().isDebugMapTileDownloader()) {
                Log.d(IMapView.LOGTAG, tileURLString + " success, mime is " + mime );
            }
            if (mime!=null && !mime.toLowerCase().contains("image")) {
                Log.w(IMapView.LOGTAG, tileURLString + " success, however the mime type does not appear to be an image " + mime );
            }

            in = c.getInputStream();

            dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, StreamUtils.IO_BUFFER_SIZE);
            final long expirationTime = computeExpirationTime(
                    c.getHeaderField(OpenStreetMapTileProviderConstants.HTTP_EXPIRES_HEADER),
                    c.getHeaderField(OpenStreetMapTileProviderConstants.HTTP_CACHECONTROL_HEADER),
                    System.currentTimeMillis());
            StreamUtils.copy(in, out);
            out.flush();
            final byte[] data = dataStream.toByteArray();
            byteStream = new ByteArrayInputStream(data);

            // Save the data to the cache
            //this is the only point in which we insert tiles to the db or local file system.

            if (pFilesystemCache != null) {
                pFilesystemCache.saveFile(pTileSource, pMapTileIndex, byteStream, expirationTime);
                byteStream.reset();
            }
            return pTileSource.getDrawable(byteStream);
        } catch (final UnknownHostException e) {
            Log.w(IMapView.LOGTAG,"UnknownHostException downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
            Counters.tileDownloadErrors++;
        } catch (final BitmapTileSourceBase.LowMemoryException e) {
            // low memory so empty the queue
            Counters.countOOM++;
            Log.w(IMapView.LOGTAG,"LowMemoryException downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
            throw new CantContinueException(e);
        } catch (final FileNotFoundException e) {
            Counters.tileDownloadErrors++;
            Log.w(IMapView.LOGTAG,"Tile not found: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
        } catch (final IOException e) {
            Counters.tileDownloadErrors++;
            Log.w(IMapView.LOGTAG,"IOException downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
        } catch (final Throwable e) {
            Counters.tileDownloadErrors++;
            Log.e(IMapView.LOGTAG,"Error downloading MapTile: " + MapTileIndex.toString(pMapTileIndex), e);
        } finally {
            StreamUtils.closeStream(in);
            StreamUtils.closeStream(out);
            StreamUtils.closeStream(byteStream);
            StreamUtils.closeStream(dataStream);
            try{
                c.disconnect();
            } catch (Exception ex){}
        }

        return null;
    }
1277740
def tile_bbox(self, tile_indices):
        
        (z, x, y) = tile_indices
        topleft = (x * self.tilesize, (y + 1) * self.tilesize)
        bottomright = ((x + 1) * self.tilesize, y * self.tilesize)
        nw = self.unproject_pixels(topleft, z)
        se = self.unproject_pixels(bottomright, z)
        return nw + se
527233
public static List<Long> getTilesCoverage(final ArrayList<GeoPoint> pGeoPoints,
                                              final int pZoomMin, final int pZoomMax) {
        final List<Long> result = new ArrayList<>();
        for (int zoomLevel = pZoomMin; zoomLevel <= pZoomMax; zoomLevel++) {
            final Collection<Long> resultForZoom = getTilesCoverage(pGeoPoints, zoomLevel);
            result.addAll(resultForZoom);
        }
        return result;
    }
883966
def createTileUrl(self, x, y, z):
        '''
        
        '''
        return self.tileTemplate.replace('{{x}}', str(x)).replace('{{y}}', str(
            y)).replace('{{z}}', str(z))
152077
public byte[] getTile( int tx, int tyOsm, int zoom ) throws Exception {
        int ty = tyOsm;
        if (tileRowType.equals("tms")) {
            int[] tmsTileXY = MercatorUtils.osmTile2TmsTile(tx, tyOsm, zoom);
            ty = tmsTileXY[1];
        }
        int _ty = ty;
        return database.execOnConnection(connection -> {
            try (IHMPreparedStatement statement = connection.prepareStatement(SELECTQUERY)) {
                statement.setInt(1, zoom);
                statement.setInt(2, tx);
                statement.setInt(3, _ty);
                IHMResultSet resultSet = statement.executeQuery();
                if (resultSet.next()) {
                    byte[] imageBytes = resultSet.getBytes(1);
                    return imageBytes;
                }
            }
            return null;
        });
    }
551581
public static TileColumn createTileColumnColumn(int index) {
		return new TileColumn(index, TileTable.COLUMN_TILE_COLUMN,
				GeoPackageDataType.INTEGER, null, true, 0, false);
	}
300191
public Collection<TileRef> getDirectTransitiveTiles(Transition transition)
    {
        final String groupOut = transition.getOut();
        final Collection<GroupTransition> currentTransitives = getTransitives(transition.getIn(), groupOut);
        if (currentTransitives.size() != 2)
        {
            return Collections.emptySet();
        }
        final GroupTransition groupTransition = currentTransitives.iterator().next();
        return mapTransition.getTiles(new Transition(transition.getType(), groupTransition.getOut(), groupOut));
    }
402835
public static void getTile (int width, int height, int tileWidth, int tileHeight, int tileIndex,
                                Rectangle bounds)
    {
        // figure out from whence to crop the tile
        int tilesPerRow = width / tileWidth;

        // if we got a bogus region, return bogus tile bounds
        if (tilesPerRow == 0) {
            bounds.setBounds(0, 0, width, height);

        } else {
            int row = tileIndex / tilesPerRow;
            int col = tileIndex % tilesPerRow;
            // crop the tile-sized image chunk from the full image
            bounds.setBounds(tileWidth*col, tileHeight*row, tileWidth, tileHeight);
        }
    }
1185758
public static Rectangle getTile (
        int width, int height, int tileWidth, int tileHeight, int tileIndex)
    {
        Rectangle bounds = new Rectangle();
        getTile(width, height, tileWidth, tileHeight, tileIndex, bounds);
        return bounds;
    }
364035
def quad_tree(self):
        """"""
        value = ''
        tms_x, tms_y = self.tms
        tms_y = (2 ** self.zoom - 1) - tms_y
        for i in range(self.zoom, 0, -1):
            digit = 0
            mask = 1 << (i - 1)
            if (tms_x & mask) != 0:
                digit += 1
            if (tms_y & mask) != 0:
                digit += 2
            value += str(digit)
        return value
836059
def from_tms(cls, tms_x, tms_y, zoom):
        """"""
        max_tile = (2 ** zoom) - 1
        assert 0 <= tms_x <= max_tile, 'TMS X needs to be a value between 0 and (2^zoom) -1.'
        assert 0 <= tms_y <= max_tile, 'TMS Y needs to be a value between 0 and (2^zoom) -1.'
        return cls(tms_x=tms_x, tms_y=tms_y, zoom=zoom)