### Install Documentation Dependencies Source: https://github.com/developmentseed/morecantile/blob/main/CONTRIBUTING.md Clone the repository and install documentation-specific dependencies using uv. ```bash git clone https://github.com/developmentseed/morecantile.git cd morecantile uv sync --group docs ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/developmentseed/morecantile/blob/main/CONTRIBUTING.md Clone the repository and install development dependencies using uv, including the rasterio extra. ```bash git clone https://github.com/developmentseed/morecantile.git cd morecantile uv sync --extra rasterio ``` -------------------------------- ### Install Benchmark Dependencies and Run Performance Tests Source: https://github.com/developmentseed/morecantile/blob/main/CONTRIBUTING.md Install benchmark-specific dependencies and run performance tests using uv and pytest. ```bash uv sync --group benchmark uv run pytest tests/benchmarks.py --benchmark-only --benchmark-columns 'min, max, mean, median' --benchmark-sort 'min' ``` -------------------------------- ### Example: Querying Tiles Source: https://github.com/developmentseed/morecantile/blob/main/docs/src/cli.md An example demonstrating how to use the 'tiles' command to find tiles at zoom level 12 that intersect with a given bounding box. The output is a JSON array of [x, y, z] tile coordinates. ```bash $ echo "[-105.05, 39.95, -105, 40]" | morecantile tiles 12 ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/developmentseed/morecantile/blob/main/CONTRIBUTING.md Start a local development server for hot-reloading documentation using uv and mkdocs. ```bash uv run mkdocs serve -f docs/mkdocs.yml ``` -------------------------------- ### Install pre-commit Hooks Source: https://github.com/developmentseed/morecantile/blob/main/CONTRIBUTING.md Set up pre-commit hooks for code formatting and linting using uv. ```bash uv run pre-commit install ``` -------------------------------- ### Install Dependencies and Run Benchmarks Source: https://github.com/developmentseed/morecantile/blob/main/benchmarks/README.md Installs necessary dependencies from requirements.txt and runs the pytest benchmarks. Use --benchmark-only to run only benchmarks and --benchmark-columns to specify displayed columns. Sort results by minimum execution time. ```sh python -m pip install -r requirements.txt ``` ```sh python -m pytest benchmarks.py --benchmark-only --benchmark-columns 'min, max, mean, median' --benchmark-sort 'min' ``` -------------------------------- ### Install Morecantile Source: https://github.com/developmentseed/morecantile/blob/main/README.md Install Morecantile using pip. You can install the latest version from PyPI or directly from the source repository. ```bash python -m pip install -U pip python -m pip install morecantile ``` ```bash python -m pip install -U pip python -m pip install git+https://github.com/developmentseed/morecantile.git ``` -------------------------------- ### Get and Print TileMatrixSet JSON Source: https://github.com/developmentseed/morecantile/blob/main/CHANGES.md Demonstrates how to retrieve a predefined TileMatrixSet and print its JSON representation. This is useful for inspecting the configuration of a TMS. ```python from morecantile import tms tms.get("WorldCRS84Quad") >>> print(tms.get("WorldCRS84Quad").json()) >>> { 'type': 'TileMatrixSetType', 'title': 'CRS84 for the World', 'abstract': None, 'keywords': None, 'identifier': 'WorldCRS84Quad', 'supportedCRS': CRS.from_epsg(4326), 'wellKnownScaleSet': AnyHttpUrl(...), 'boundingBox': { 'type': 'BoundingBoxType', 'crs': CRS.from_epsg(4326), 'lowerCorner': (-180.0, -90.0), 'upperCorner': (180.0, 90.0)}, 'tileMatrix': [...] } ``` -------------------------------- ### TileMatrixSet Management Source: https://context7.com/developmentseed/morecantile/llms.txt This section covers how to list, get, and inspect available TileMatrixSets provided by Morecantile. ```APIDOC ## TileMatrixSet Management ### Description Retrieve and manage TileMatrixSet objects. Morecantile includes several built-in grids and allows for custom definitions. ### Methods #### List all available TileMatrixSets ```python import morecantile print(morecantile.tms.list()) ``` #### Get a specific TileMatrixSet by identifier ```python import morecantile tms = morecantile.tms.get("WebMercatorQuad") print(tms) ``` ### Properties of a TileMatrixSet #### Accessing TileMatrixSet properties ```python # Assuming 'tms' is a loaded TileMatrixSet object print(f"Min zoom: {tms.minzoom}, Max zoom: {tms.maxzoom}") print(tms.xy_bbox) print(tms.bbox) ``` ### Response Example (TMS Properties) ```json { "minzoom": 0, "maxzoom": 24, "xy_bbox": { "left": -20037508.342789244, "bottom": -20037508.34278919, "right": 20037508.34278919, "top": 20037508.342789244 }, "bbox": { "left": -180.0, "bottom": -85.0511287798066, "right": 180.0, "top": 85.0511287798066 } } ``` ``` -------------------------------- ### List and Get TileMatrixSets Source: https://context7.com/developmentseed/morecantile/llms.txt Retrieve and inspect available TileMatrixSets. Use `morecantile.tms.list()` to see all available grids and `morecantile.tms.get()` to load a specific one. Properties like min/max zoom and bounding boxes are accessible. ```python import morecantile # List all available TileMatrixSets print(morecantile.tms.list()) # Output: ['CDB1GlobalGrid', 'CanadianNAD83_LCC', 'EuropeanETRS89_LAEAQuad', # 'GNOSISGlobalGrid', 'LINZAntarticaMapTilegrid', 'NZTM2000Quad', # 'UPSAntarcticWGS84Quad', 'UPSArcticWGS84Quad', 'UTM31WGS84Quad', # 'WebMercatorQuad', 'WGS1984Quad', 'WorldCRS84Quad', 'WorldMercatorWGS84Quad'] # Get Web Mercator TMS (most common for web maps) tms = morecantile.tms.get("WebMercatorQuad") print(tms) # Output: l3.geojson ``` -------------------------------- ### CLI: Get Tiles for Bounding Box Source: https://context7.com/developmentseed/morecantile/llms.txt Calculates and outputs the tile coordinates (x, y, z) that intersect a given bounding box at a specified zoom level. ```bash # Get tiles for a bounding box at zoom level 12 echo "[-105.05, 39.95, -105, 40]" | morecantile tiles 12 # Output: # [852, 1550, 12] # [852, 1551, 12] # [853, 1550, 12] # [853, 1551, 12] ``` -------------------------------- ### Get Tile from Bounding Box Source: https://github.com/developmentseed/morecantile/blob/main/benchmarks/README.md Calculate the tiles that intersect with a given bounding box for a specific zoom level. Requires a TileMatrixSet. ```python from morecantile import tms webmercator = tms.get("WebMercator") # Bounding box in WebMercator coordinates bbox = (-74.0, 40.7, -73.9, 40.8) tiles = list(webmercator.tiles(*bbox, zooms=12)) print(tiles) ``` -------------------------------- ### Get TileMatrixSet by ID Source: https://github.com/developmentseed/morecantile/blob/main/benchmarks/README.md Retrieve a predefined TileMatrixSet using its unique identifier. Supports common grids like WebMercator. ```python from morecantile import tms webmercator = tms.get("WebMercator") ``` -------------------------------- ### Get Matrix Info at Zoom 0 Source: https://context7.com/developmentseed/morecantile/llms.txt Retrieves and prints matrix dimensions and cell size for a given TileMatrixSet at zoom level 0. ```python matrix = custom_tms.matrix(0) print(f"Matrix width: {matrix.matrixWidth}, height: {matrix.matrixHeight}") print(f"Cell size: {matrix.cellSize}") ``` -------------------------------- ### CLI: Get Tiles with Different TMS Source: https://context7.com/developmentseed/morecantile/llms.txt Calculates tiles for a bounding box using a specified TileMatrixSet identifier, allowing for operations with non-standard CRS. ```bash # Use a different TileMatrixSet echo "[-105.05, 39.95, -105, 40]" | morecantile tiles 8 --identifier WorldCRS84Quad ``` -------------------------------- ### Get Bounding Box from Tile Source: https://github.com/developmentseed/morecantile/blob/main/benchmarks/README.md Convert a tile object back into its geographic bounding box coordinates. Requires the TileMatrixSet. ```python from morecantile import tms, Tile webmercator = tms.get("WebMercator") tile = Tile(x=123, y=456, z=10) bbox = webmercator.bounds(tile) print(bbox) ``` -------------------------------- ### Create Tiles and Get Bounds Source: https://context7.com/developmentseed/morecantile/llms.txt Instantiate `morecantile.Tile` objects and calculate their bounding boxes. Use `tms.xy_bounds()` for bounds in the TMS's native CRS and `tms.bounds()` for geographic (WGS84) bounds. `tms.ul()` and `tms.lr()` provide upper-left and lower-right corners. ```python import morecantile tms = morecantile.tms.get("WebMercatorQuad") # Create a tile using the Tile namedtuple tile = morecantile.Tile(x=10, y=10, z=4) # Get tile bounds in TMS CRS (EPSG:3857 meters) xy_bounds = tms.xy_bounds(tile) print(xy_bounds) # Output: BoundingBox(left=5009377.085697308, bottom=-7514065.628545959, right=7514065.628545959, top=-5009377.085697308) # Get tile bounds in geographic coordinates (WGS84 degrees) geo_bounds = tms.bounds(tile) print(geo_bounds) # Output: BoundingBox(left=44.999999999999964, bottom=-55.776573018667634, right=67.4999999999999, top=-40.97989806962009) # Get upper-left corner in geographic coordinates ul = tms.ul(tile) print(ul) # Output: Coords(x=44.999999999999964, y=-40.97989806962009) # Get lower-right corner in geographic coordinates lr = tms.lr(tile) print(lr) # Output: Coords(x=67.4999999999999, y=-55.776573018667634) # Get upper-left corner in TMS CRS ul_xy = tms._ul(tile) print(ul_xy) # Output: Coords(x=5009377.085697308, y=-5009377.085697308) ``` -------------------------------- ### Get tile bounds Source: https://github.com/developmentseed/morecantile/blob/main/docs/src/usage.md Calculates the bounding box for a given tile. Supports both the tile's native CRS (xy_bounds) and WGS84 (bounds). ```python import morecantile tms = morecantile.tms.get("WebMercatorQuad") # Get the bounds for tile Z=4, X=10, Y=10 in the input projection tms.xy_bounds(morecantile.Tile(10, 10, 4)) ``` ```python # Get the bounds for tile Z=4, X=10, Y=10 in LatLon (WGS84) tms.bounds(morecantile.Tile(10, 10, 4)) ``` -------------------------------- ### Accessing CRS information in morecantile Source: https://github.com/developmentseed/morecantile/blob/main/CHANGES.md This example demonstrates how to retrieve the CRS URI and EPSG code from a TileMatrixSet object using the `crs` and `_crs` attributes. It also shows the internal pyproj CRS object. ```python import morecantile tms = morecantile.tms.get("WebMercatorQuad") tms.crs >> CRSType(__root__='http://www.opengis.net/def/crs/EPSG/0/3857') tms.crs.to_epsg() >> 3857 tms._crs >> tms._crs.to_epsg() >> 3857 ``` -------------------------------- ### List Supported Tile Matrix Sets Source: https://github.com/developmentseed/morecantile/blob/main/docs/src/usage.md Use this function to retrieve a list of all available Tile Matrix Sets (TMS) supported by Morecantile. No setup is required. ```python import morecantile print(morecantile.tms.list()) ``` -------------------------------- ### Get CRS Information Source: https://context7.com/developmentseed/morecantile/llms.txt Accesses coordinate reference system details from a TileMatrixSet, providing EPSG code, WKT representation, and PROJ4 string. ```python import morecantile tms = morecantile.tms.get("WebMercatorQuad") # Get CRS as EPSG code epsg = tms.crs.to_epsg() print(f"EPSG: {epsg}") # Output: EPSG: 3857 # Get CRS as WKT wkt = tms.crs.to_wkt() print(wkt[:100] + "...") # Get CRS as PROJ4 string proj4 = tms.crs.to_proj4() print(proj4) # Output: +proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs ``` -------------------------------- ### Allow CRS parsing with WKT or URI in TileMatrixSet Source: https://github.com/developmentseed/morecantile/blob/main/CHANGES.md Version 5.2.0 introduced flexibility in CRS parsing for TileMatrixSet, allowing WKT or URI formats. Examples demonstrate setting CRS via a URI string, a URI dictionary, and a WKT dictionary. ```python TileMatrixSet( ... crs="http://www.opengis.net/def/crs/EPSG/0/3857" ) TileMatrixSet( ... crs={"uri": "http://www.opengis.net/def/crs/EPSG/0/3857"} ) wkt = pyproj.CRS.from_epsg(3857).to_wkt() TileMatrixSet( ... crs={"wkt": wkt} ) ``` -------------------------------- ### Generate GeoJSON Shapes from TMS Source: https://github.com/developmentseed/morecantile/blob/main/docs/src/cli.md This example generates GeoJSON shapes for zoom level 4 of the 'EuropeanETRS89_LAEAQuad' TMS, collecting the output into a GeoJSON feature collection. ```bash $ rio bounds eu.tif | morecantile tiles 4 --identifier EuropeanETRS89_LAEAQuad | morecantile shapes --identifier EuropeanETRS89_LAEAQuad --collect > z4.geojson ``` -------------------------------- ### Get Tile Bounds in Native CRS Source: https://github.com/developmentseed/morecantile/blob/main/README.md Calculate the bounding box for a specific tile (z, x, y) within the TileMatrixSet's native coordinate reference system. ```python import morecantile tms = morecantile.tms.get("WebMercatorQuad") # Get the bounds for tile Z=4, X=10, Y=10 in the TMS's CRS (e.g epsg:3857) print(tms.xy_bounds(morecantile.Tile(10, 10, 4))) >>> BoundingBox( left=5009377.085697308, bottom=-7514065.628545959, right=7514065.628545959, top=-5009377.085697308, ) ``` -------------------------------- ### Find Zoom Level for Resolution Source: https://context7.com/developmentseed/morecantile/llms.txt Determines the appropriate zoom level for a given resolution using different strategies (auto, lower, upper). Also shows how to get the actual resolution at a specific zoom level. ```python import morecantile tms = morecantile.tms.get("WebMercatorQuad") # Get zoom level for a resolution (in TMS units, meters for WebMercatorQuad) resolution = 612.0 # meters per pixel # Auto strategy: pick closest zoom level zoom = tms.zoom_for_res(resolution) print(f"Zoom for {resolution}m resolution: {zoom}") # Force lower zoom level zoom_lower = tms.zoom_for_res(resolution, zoom_level_strategy="lower") print(f"Lower zoom: {zoom_lower}") # Force upper zoom level zoom_upper = tms.zoom_for_res(resolution, zoom_level_strategy="upper") print(f"Upper zoom: {zoom_upper}") # Get the actual resolution at a zoom level matrix = tms.matrix(8) print(f"Resolution at zoom 8: {matrix.cellSize} meters/pixel") # Output: Resolution at zoom 8: 611.4962... meters/pixel ``` -------------------------------- ### CLI: Get Tile Shapes as GeoJSON Source: https://context7.com/developmentseed/morecantile/llms.txt Retrieves the geographic boundaries of a tile as a GeoJSON feature. Use --collect to get a FeatureCollection for multiple tiles. ```bash # Get tile shapes as GeoJSON echo "[852, 1550, 12]" | morecantile shapes # Output: GeoJSON feature # Get tile shapes as GeoJSON FeatureCollection echo -e "[852, 1550, 12]\n[853, 1550, 12]" | morecantile shapes --collect ``` -------------------------------- ### Deploy Documentation Source: https://github.com/developmentseed/morecantile/blob/main/CONTRIBUTING.md Manually deploy the documentation to GitHub Pages using uv and mkdocs. Note: This is typically handled automatically by GitHub Actions. ```bash uv run mkdocs gh-deploy -f docs/mkdocs.yml ``` -------------------------------- ### Run Tests Source: https://github.com/developmentseed/morecantile/blob/main/CONTRIBUTING.md Execute the test suite with coverage reporting using uv. ```bash uv run pytest --cov morecantile --cov-report term-missing -s -vv ``` -------------------------------- ### Convert Tile to Quadkey and Vice Versa Source: https://github.com/developmentseed/morecantile/blob/main/CHANGES.md Demonstrates how to convert between tile coordinates and quadkey strings using a specified TileMatrixSet. Ensure the TileMatrixSet is correctly initialized. ```python import morecantile tms = morecantile.tms.get("WebMercatorQuad") # Tile to Quadkey tms.quadkey(486, 332, 10) >>> "0313102310" # Quadkey to Tile tms.quadkey_to_tile("0313102310") >>> Tile(486, 332, 10) ``` -------------------------------- ### Get CanadianNAD83_LCC Geographic CRS Source: https://github.com/developmentseed/morecantile/blob/main/docs/src/advanced/geographic.md Retrieves the default geographic CRS for the CanadianNAD83_LCC TileMatrixSet, which is NAD83 (EPSG:4269). ```python morecantile.tms.get("CanadianNAD83_LCC").geographic_crs >> Name: NAD83 Axis Info [ellipsoidal]: - Lat[north]: Geodetic latitude (degree) - Lon[east]: Geodetic longitude (degree) Area of Use: - name: North America - onshore and offshore: Canada - Alberta; British Columbia; Manitoba; New Brunswick; Newfoundland and Labrador; Northwest Territories; Nova Scotia; Nunavut; Ontario; Prince Edward Island; Quebec; Saskatchewan; Yukon. Puerto Rico. United States (USA) - Alabama; Alaska; Arizona; Arkansas; California; Colorado; Connecticut; Delaware; Florida; Georgia; Hawaii; Idaho; Illinois; Indiana; Iowa; Kansas; Kentucky; Louisiana; Maine; Maryland; Massachusetts; Michigan; Minnesota; Mississippi; Missouri; Montana; Nebraska; Nevada; New Hampshire; New Jersey; New Mexico; New York; North Carolina; North Dakota; Ohio; Oklahoma; Oregon; Pennsylvania; Rhode Island; South Carolina; South Dakota; Tennessee; Texas; Utah; Vermont; Virginia; Washington; West Virginia; Wisconsin; Wyoming. US Virgin Islands. British Virgin Islands. - bounds: (167.65, 14.92, -40.73, 86.45) Datum: North American Datum 1983 - Ellipsoid: GRS 1980 - Prime Meridian: Greenwich ``` -------------------------------- ### Load TileMatrixSet from JSON Source: https://context7.com/developmentseed/morecantile/llms.txt Demonstrates loading a TileMatrixSet from a JSON file or a Python dictionary, and exporting it back to JSON or a dictionary. ```python import morecantile import json # Load from JSON file using Pydantic's model_validate_json with open("my_tms.json", "r") as f: tms = morecantile.TileMatrixSet.model_validate_json(f.read()) # Load from dictionary tms_dict = { "id": "ExampleTMS", "title": "Example TileMatrixSet", "crs": "http://www.opengis.net/def/crs/EPSG/0/3857", "tileMatrices": [ { "id": "0", "scaleDenominator": 559082264.0287178, "cellSize": 156543.03392804097, "pointOfOrigin": [-20037508.342789244, 20037508.342789244], "tileWidth": 256, "tileHeight": 256, "matrixWidth": 1, "matrixHeight": 1 } ] } tms = morecantile.TileMatrixSet(**tms_dict) # Export TMS to JSON json_str = tms.model_dump_json(exclude_none=True) print(json_str) # Export to dictionary tms_export = tms.model_dump(exclude_none=True) ``` -------------------------------- ### Morecantile CLI Help Source: https://github.com/developmentseed/morecantile/blob/main/docs/src/cli.md Displays general help information for the Morecantile CLI, outlining available commands and global options. ```bash morecantile --help ``` -------------------------------- ### Get WebMercatorQuad Geographic CRS Source: https://github.com/developmentseed/morecantile/blob/main/docs/src/advanced/geographic.md Retrieves the default geographic CRS for the WebMercatorQuad TileMatrixSet, which is typically WGS84 (EPSG:4326). ```python import morecantile morecantile.tms.get("WebMercatorQuad").geographic_crs >> Name: WGS 84 Axis Info [ellipsoidal]: - Lat[north]: Geodetic latitude (degree) - Lon[east]: Geodetic longitude (degree) Area of Use: - name: World. - bounds: (-180.0, -90.0, 180.0, 90.0) Datum: World Geodetic System 1984 ensemble - Ellipsoid: WGS 84 - Prime Meridian: Greenwich ``` -------------------------------- ### Initialize Benchmark Data Rendering Source: https://github.com/developmentseed/morecantile/blob/main/docs/src/benchmark.html Initializes the benchmark data rendering process. It prepares data points for charts by collecting benches per test case and renders the header and footer elements of the benchmark page. Requires the benchmark data as input. ```javascript 'use strict'; (function() { // Colors from https://github.com/github/linguist/blob/master/lib/linguist/languages.yml const toolColors = { cargo: '#dea584', go: '#00add8', benchmarkjs: '#f1e05a', benchmarkluau: '#000080', pytest: '#3572a5', googlecpp: '#f34b7d', catch2: '#f34b7d', julia: '#a270ba', jmh: '#b07219', benchmarkdotnet: '#178600', customBiggerIsBetter: '#38ff38', customSmallerIsBetter: '#ff3838', _: '#333333' }; function init(data) { function collectBenchesPerTestCase(entries) { const map = new Map(); for (const entry of entries) { const {commit, date, tool, benches} = entry; for (const bench of benches) { const result = { commit, date, tool, bench }; const arr = map.get(bench.name); if (arr === undefined) { map.set(bench.name, [result]); } else { arr.push(result); } } } return map; } // Render header document.getElementById('last-update').textContent = new Date(data.lastUpdate).toString(); const repoLink = document.getElementById('repository-link'); repoLink.href = data.repoUrl; repoLink.textContent = data.repoUrl; // Render footer document.getElementById('dl-button').onclick = () => { const dataUrl = 'data:,' + JSON.stringify(data, null, 2); const a = document.createElement('a'); a.href = dataUrl; a.download = 'benchmark_data.json'; a.click(); }; // Prepare data points for charts return Object.keys(data.entries).map(name => ({ name, dataSet: collectBenchesPerTestCase(data.entries[name]), })); } function renderAllChars(dataSets) { function renderGraph(parent, name, dataset) { const canvas = document.createElement('canvas'); canvas.className = 'benchmark-chart'; parent.appendChild(canvas); const color = toolColors[dataset.length > 0 ? dataset[0].tool : '_']; const data = { labels: dataset.map(d => d.commit.id.slice(7)), datasets: [ { label: name, data: dataset.map(d => d.bench.value), borderColor: color, backgroundColor: color + '60', // Add alpha for #rrggbbaa }, ], }; const options = { scales: { xAxes: [ { scaleLabel: { display: true, labelString: 'commit', }, } ], yAxes: [ { scaleLabel: { display: true, labelString: dataset.length > 0 ? dataset[0].bench.unit : '', }, ticks: { beginAtZero: true, } } ], }, tooltips: { callbacks: { afterTitle: items => { const {index} = items[0]; const data = dataset[index]; return '\n' + data.commit.message + '\n\n' + data.commit.timestamp + ' committed by @' + data.commit.committer.username + '\n'; }, label: item => { let label = item.value; const { range, unit } = dataset[item.index].bench; label += ' ' + unit; if (range) { label += ' (' + range + ')'; } return label; }, afterLabel: item => { const { extra } = dataset[item.index].bench; return extra ? '\n' + extra : ''; } } }, onClick: (_mouseEvent, activeElems) => { if (activeElems.length === 0) { return; } // XXX: Undocumented. How can we know the index? const index = activeElems[0]._index; const url = dataset[index].commit.url; window.open(url, '_blank'); }, }; new Chart(canvas, { type: 'line', data, options }); } function renderBenchSet(name, benchSet, main) { const setElem = document.createElement('div'); setElem.className = 'benchmark-set'; main.appendChild(setElem); const nameElem = document.createElement('h1'); nameElem.className = 'benchmark-title'; nameElem.textContent = name; setElem.appendChild(nameElem); const graphsElem = document.createElement('div'); graphsElem.className = 'benchmark-graphs'; setElem.appendChild(graphsElem); for (const [benchName, benches] of benchSet.entries()) { renderGraph(graphsElem, benchName, benches) } } const main = document.getElementById('main'); for (const dataSet of dataSets) { renderBenchSet(dataSet.name, dataSet.dataSet, main); } } // Fetch data and initialize rendering fetch('/benchmark_data.json') .then(response => response.json()) .then(data => { const dataSets = init(data); renderAllChars(dataSets); }); })(); ``` -------------------------------- ### Get TMS Bounding Box Source: https://github.com/developmentseed/morecantile/blob/main/README.md Retrieve the bounding box of a TileMatrixSet in its native CRS (e.g., EPSG:3857 for WebMercatorQuad). ```python import morecantile tms = morecantile.tms.get("WebMercatorQuad") # Get TMS bounding box print(tms.xy_bbox) >>> BoundingBox( left=-20037508.342789244, bottom=-20037508.34278919, right=20037508.34278919, top=20037508.342789244, ) ``` -------------------------------- ### Create Custom TileMatrixSet (TMS) Source: https://github.com/developmentseed/morecantile/blob/main/docs/src/cli.md Use the `custom` command to create a new TileMatrixSet document. Requires EPSG and extent. Optional parameters include zoom levels, tile dimensions, and TMS identifier. ```bash $ morecantile custom --help ``` -------------------------------- ### Custom TileMatrixSet Creation Source: https://github.com/developmentseed/morecantile/blob/main/docs/src/cli.md Create custom TileMatrixSet documents using the `custom` command. ```APIDOC ## POST /api/custom ### Description Create custom TileMatrixSet documents. ### Method POST ### Endpoint /api/custom ### Parameters #### Query Parameters - **epsg** (INTEGER) - Required - EPSG number. - **extent** (FLOAT...) - Required - left, bottom, right, top Bounding box of the Tile Matrix Set. - **name** (TEXT) - Optional - Identifier of the custom TMS. - **minzoom** (INTEGER) - Optional - Minimum Zoom level. - **maxzoom** (INTEGER) - Optional - Maximum Zoom level. - **tile-width** (INTEGER) - Optional - Width of each tile. - **tile-height** (INTEGER) - Optional - Height of each tile. - **extent-epsg** (INTEGER) - Optional - EPSG number for the bounding box. - **title** (TEXT) - Optional - Tile Matrix Set title. ### Request Example ```json { "epsg": 3413, "extent": [-4194300, -4194300, 4194300, 4194300], "minzoom": 0, "maxzoom": 8, "tile-width": 512, "tile-height": 512 } ``` ### Response #### Success Response (200) - **TMS Document** (JSON) - The created TileMatrixSet document. #### Response Example ```json { "bounds": [-4194300.0, -4194300.0, 4194300.0, 4194300.0], "minzoom": 0, "maxzoom": 8, "name": "custom", "tile_height": 512, "tile_width": 512, "version": "1.0.0", "well_known_scale_set": "custom" } ``` ``` -------------------------------- ### Morecantile Tiles Command Help Source: https://github.com/developmentseed/morecantile/blob/main/docs/src/cli.md Shows help for the 'tiles' command, detailing how to list tiles intersecting with geographic data. It explains input formats and available options for specifying TileMatrixSet and output. ```bash $ morecantile tiles --help ``` -------------------------------- ### Get Tile from Geographic Coordinates Source: https://github.com/developmentseed/morecantile/blob/main/benchmarks/README.md Determine the tile that contains a given geographic point (longitude, latitude) at a specific zoom level. Requires a TileMatrixSet. ```python from morecantile import tms webmercator = tms.get("WebMercator") # Longitude, Latitude lon, lat = -74.0, 40.7 tile = webmercator.tile(lon, lat, 12) print(tile) ``` -------------------------------- ### Get Tile Bounds in Geographic CRS Source: https://github.com/developmentseed/morecantile/blob/main/README.md Calculate the bounding box for a specific tile (z, x, y) and convert it to geographic coordinates (e.g., EPSG:4326). ```python import morecantile tms = morecantile.tms.get("WebMercatorQuad") # Get the bounds for tile Z=4, X=10, Y=10 in Geographic CRS (e.g epsg:4326) print(tms.bounds(morecantile.Tile(10, 10, 4))) >>> BoundingBox( left=44.999999999999964, bottom=-55.776573018667634, right=67.4999999999999, top=-40.97989806962009, ) ``` -------------------------------- ### Register and List Custom TMS Source: https://github.com/developmentseed/morecantile/blob/main/CHANGES.md This snippet demonstrates how to set the TILEMATRIXSET_DIRECTORY environment variable to load custom TMS from a specified path and then verify its registration using `tms.list()`. ```python import os os.environ["TILEMATRIXSET_DIRECTORY"] = "/tmp/mytms" from morecantile import tms assert "MyCustomTmsEPSG3031" in tms.list() ``` -------------------------------- ### CLI: Create Custom TileMatrixSet JSON Source: https://context7.com/developmentseed/morecantile/llms.txt Generates a custom TileMatrixSet JSON document from the command line, specifying CRS, extent, and other parameters. The output can be redirected to a file. ```bash # Create a custom TMS for EPSG:32631 (UTM zone 31N) morecantile custom \ --epsg 32631 \ --extent 166000 0 834000 9400000 \ --name "UTM31N_Custom" \ --title "Custom UTM Zone 31N TileMatrixSet" \ --minzoom 0 \ --maxzoom 18 \ --tile-width 256 \ --tile-height 256 > utm31n_custom.json # Create TMS with extent in different CRS morecantile custom \ --epsg 3857 \ --extent -180 -85 180 85 \ --extent-epsg 4326 \ --name "WebMercator_Custom" ``` -------------------------------- ### Fetch and Render Benchmark Data Source: https://github.com/developmentseed/morecantile/blob/main/docs/src/benchmark.html Fetches benchmark data from a specified URL, parses it, and initiates rendering. Handles network errors and JSON parsing. Ensure the URL is accessible and the data format is correct. ```javascript fetch('https://raw.githubusercontent.com/developmentseed/morecantile/gh-benchmarks/dev/benchmarks/data.js') .then(res => { if (res.ok) return res.text() throw new Error('Network response was not ok.') }) .then(data => { const data_json = JSON.parse(data.replace('window.BENCHMARK_DATA = ', '')); renderAllChars(init(data_json)) return }) .catch(err => { console.log(err) }); ``` -------------------------------- ### Get GeoJSON Feature for a tile Source: https://github.com/developmentseed/morecantile/blob/main/docs/src/usage.md Generates a GeoJSON Feature object representing a specific tile, including its bounding box and geometry. This is useful for visualization or interoperability. ```python import morecantile tms = morecantile.tms.get("WebMercatorQuad") tms.feature(morecantile.Tile(10, 10, 4)) ``` -------------------------------- ### Create Custom TileMatrixSets Source: https://context7.com/developmentseed/morecantile/llms.txt Enables the creation of custom TileMatrixSets for any coordinate reference system, defining extent, CRS, zoom levels, and tile dimensions. ```python import morecantile from pyproj import CRS # Create a custom TMS for Antarctic Polar Stereographic (EPSG:3031) crs = CRS.from_epsg(3031) extent = [-948.75, -543592.47, 5817.41, -3333128.95] custom_tms = morecantile.TileMatrixSet.custom( extent=extent, crs=crs, id="MyAntarcticTMS", title="Custom Antarctic TileMatrixSet", minzoom=0, maxzoom=18, tile_width=256, tile_height=256, ) print(custom_tms) # Output: >> 10 defaults = tms.register(custom_tms) print(len(tms.list())) >>> 10 print(len(defaults.list())) >>> 11 ``` -------------------------------- ### Register Custom TileMatrixSet Source: https://context7.com/developmentseed/morecantile/llms.txt Adds a custom TileMatrixSet to the default registry for easy access. Note that the original registry is immutable, and registration returns a new instance. ```python import morecantile from pyproj import CRS # Create a custom TMS custom_tms = morecantile.TileMatrixSet.custom( extent=[-180, -90, 180, 90], crs=CRS.from_epsg(4326), id="MyCustomTMS", ) # Register it (returns a new TileMatrixSets instance) extended_tms = morecantile.tms.register({"MyCustomTMS": custom_tms}) # Now you can access it like built-in TileMatrixSets print("MyCustomTMS" in extended_tms.list()) # Output: True my_tms = extended_tms.get("MyCustomTMS") # Note: Original morecantile.tms is immutable print("MyCustomTMS" in morecantile.tms.list()) # Output: False ``` -------------------------------- ### Convert Between Tiles and Quadkeys Source: https://context7.com/developmentseed/morecantile/llms.txt Handles conversions between morecantile Tile objects and quadkey strings. This functionality is supported for quadtree-compatible TileMatrixSets. ```python import morecantile tms = morecantile.tms.get("WebMercatorQuad") # Check if TMS supports quadkeys print(f"Supports quadkeys: {tms.is_quadtree}") # Output: Supports quadkeys: True ``` ```python # Convert tile to quadkey tile = morecantile.Tile(486, 332, 10) quadkey = tms.quadkey(tile) print(quadkey) # Output: "0313102310" ``` ```python # Convert quadkey back to tile tile_from_qk = tms.quadkey_to_tile("0313102310") print(tile_from_qk) # Output: Tile(x=486, y=332, z=10) ``` ```python # Empty quadkey returns root tile root_tile = tms.quadkey_to_tile("") print(root_tile) # Output: Tile(x=0, y=0, z=0) ``` -------------------------------- ### Save Custom TMS to File Source: https://github.com/developmentseed/morecantile/blob/main/CHANGES.md Use this snippet to create a custom TileMatrixSet with a specified extent and CRS, then save it as a JSON file. Ensure the directory exists before writing. ```python import morecantile from rasterio.crs import CRS crs = CRS.from_epsg(3031) extent = [-948.75, -543592.47, 5817.41, -3333128.95] # From https:///epsg.io/3031 tms = morecantile.TileMatrixSet.custom(extent, crs, identifier="MyCustomTmsEPSG3031") with open("/tmp/mytms/MyCustomTmsEPSG3031.json", "w") as f: f.write(tms.json(exclude_none=True)) ``` -------------------------------- ### Convert TMS v1 to v2.0 using Morecantile Source: https://github.com/developmentseed/morecantile/blob/main/docs/src/tms-v2.md Use the `from_v1` class method to convert a Tile Matrix Set defined using the older TMS v1 specification to the v2.0 format. Ensure the input JSON is loaded correctly. ```python from morecantile.models import TileMatrixSet import json with open("tms_v1.json") as f: data = json.load(f) TileMatrixSet.from_v1(data) ``` -------------------------------- ### Zoom Level Strategy for Resolution Source: https://github.com/developmentseed/morecantile/blob/main/CHANGES.md Illustrates how to determine the appropriate zoom level for a given resolution using different strategies. The default 'auto' strategy selects the closest zoom level. ```python import morecantile tms = morecantile.tms.get("WebMercatorQuad") # native resolution of zoom 7 is 1222.9924 m # native resolution of zoom 8 is 611.4962 m assert tms.zoom_for_res(612.0) == 8 assert tms.zoom_for_res(612.0, zoom_level_strategy="lower") == 7 assert tms.zoom_for_res(612.0, zoom_level_strategy="upper") == 8 ``` -------------------------------- ### Retrieve TileMatrixSet (TMS) Document Source: https://github.com/developmentseed/morecantile/blob/main/docs/src/cli.md The `tms` command prints a TileMatrixSet document in JSON format. Specify an identifier from the predefined list to retrieve its definition. ```bash $ morecantile tms --help ```