morecantile: Python Library for Tile Matrix Sets

repository·main·Indexed 41 days ago

https://github.com/developmentseed/morecantile

A Python library for constructing and using map tile grids (TileMatrixSets / TMS) following the OGC Two Dimensional Tile Matrix Set specification. It extends the mercantile library to support various OGC-compliant grids beyond Web Mercator, including built-in support for EPSG:4326, EPSG:3857, and others. Features include coordinate transformation between native and geographic CRS, tile lookup for points and bounding boxes, and tools to convert TMS definitions to GeoJSON.

Tokens
9.9K
Snippets
45
Records
56
Agent score
51%

What's inside morecantile

  1. Understand tileMatrixSet JSON documents

    main
    The morecantile package utilizes tileMatrixSet JSON documents to define tile grids. These documents follow the OpenGIS specification for Tile Matrix Sets (TMS) 2.0. These definitions allow the library to understand the coordinate reference systems (CRS), resolutions, and tile boundaries for specific grid systems used in web mapping and geospatial analysis.
  2. Use morecantile to work with TileMatrixSets

    main

    Morecantile allows you to construct and use map tile grids (TileMatrixSets / TMS) following the OGC Two Dimensional Tile Matrix Set specification. You can retrieve specific grids using morecantile.tms.get() and then perform spatial operations like retrieving bounding boxes for the entire grid or for specific tiles in different Coordinate Reference Systems (CRS).

    import morecantile
    
    tms = morecantile.tms.get("WebMercatorQuad")
    
    # Get the bounding box of the entire TMS
    print(tms.xy_bbox)
    
    # Get the bounds for a specific tile in the TMS's native CRS (e.g. epsg:3857)
    print(tms.xy_bounds(morecantile.Tile(10, 10, 4)))
    
    # Get the bounds for a specific tile in Geographic CRS (e.g. epsg:4326)
    print(tms.bounds(morecantile.Tile(10, 10, 4)))
  3. Install morecantile via pip

    main

    You can install morecantile from PyPI using pip. To install the latest version from the GitHub repository, use the git URL.

    python -m pip install -U pip
    python -m pip install morecantile
    
    # Or install from source:
    python -m pip install -U pip
    python -m pip install git+https://github.com/developmentseed/morecantile.git
  4. Convert TMS v1 JSON to TMS v2 TileMatrixSet

    main

    Morecantile v4 supports the updated OGC Tile Matrix Sets (TMS) v2.0 specification. If you have an existing TMS JSON document following the older v1 specification, you can convert it to a v2-compliant TileMatrixSet using the TileMatrixSet.from_v1() class method.

    This is useful when migrating legacy tile matrix definitions to the new standard which includes renamed properties like id (formerly identifier), crs (formerly supportedCRS), and pointOfOrigin (formerly topLeftCorner).

    from morecantile.models import TileMatrixSet
    import json
    
    with open("tms_v1.json") as f:
        data = json.load(f)
    
    # Convert the v1 dictionary to a v2 TileMatrixSet
    tms_v2 = TileMatrixSet.from_v1(data)
  5. Overwrite the TileMatrixSet geographic CRS

    main

    You can change the Geographic CRS used by a TileMatrixSet instance using two different methods:

    1. Instance Method: Use set_geographic_crs(crs) to overwrite the geographic CRS for a specific TileMatrixSet instance. This requires a pyproj.CRS object.
    2. Environment Variable: Set the MORECANTILE_DEFAULT_GEOGRAPHIC_CRS environment variable to change the default geographic CRS globally for all TileMatrixSet objects loaded after the variable is set.
    # Method 1: Using set_geographic_crs
    import morecantile
    import pyproj
    
    tms = morecantile.tms.get("CanadianNAD83_LCC")
    tms.set_geographic_crs(pyproj.CRS.from_epsg(4326))
    
    # Method 2: Using environment variable
    import os
    os.environ["MORECANTILE_DEFAULT_GEOGRAPHIC_CRS"] = "EPSG:4326"
    import morecantile
    
    tms = morecantile.tms.get("CanadianNAD83_LCC")
  6. Run benchmarks for morecantile

    main

    You can compare the performance of morecantile against mercantile and utiles by running the benchmark suite using pytest and pytest-benchmark.

    First, install the necessary dependencies:

    python -m pip install -r requirements.txt

    Then, execute the benchmark script with specific flags to filter for benchmarks and sort the results by minimum execution time:

    python -m pytest benchmarks.py --benchmark-only --benchmark-columns 'min, max, mean, median' --benchmark-sort 'min'
    python -m pip install -r requirements.txt
    python -m pytest benchmarks.py --benchmark-only --benchmark-columns 'min, max, mean, median' --benchmark-sort 'min'
  7. Manage and register TMS grids

    main

    Morecantile uses a TileMatrixSets store to manage available grids.

    • List grids: Use morecantile.tms.list() to see all currently registered grids.
    • Register custom grid: Use morecantile.tms.register({id: tms_object}) to add a custom TileMatrixSet to the store. This returns a new store instance.
    • Automatic registration: Set the TILEMATRIXSET_DIRECTORY environment variable to a directory containing .json files. Morecantile will automatically load these.
      • Note: Filenames must match the TMS id and contain only alphanumeric characters or underscores [a-zA-Z0-9_].
    import morecantile
    
    # List all
    print(morecantile.tms.list())
    
    # Register custom
    new_tms_store = morecantile.tms.register({"MyCustomTmsEPSG3031": custom_tms_object})
    tms = new_tms_store.get("MyCustomTmsEPSG3031")
  8. Use the Morecantile CLI

    main

    The Morecantile CLI provides several commands to interact with TileMatrixSets (TMS), convert tile descriptions to GeoJSON, and find tiles overlapping specific geometries.

    Global options include:

    • --verbose, -v: Increase verbosity.
    • --quiet, -q: Decrease verbosity.
    • --version: Show version information.
    # Example of using the CLI (assuming it is installed as `morecantile`)
    $ morecantile --help
  9. Transform coordinates using TileMatrixSet geographic methods

    main

    The morecantile.TileMatrixSet object provides several methods to transform coordinates between the Tile Matrix Set's (TMS) native Coordinate Reference System (CRS) and a Geographic CRS.

    By default, these methods use the TMS's defined geographic CRS (CRS.geodetic_crs). Common examples include WGS84 (EPSG:4326), though this varies by TMS.

    Available Methods:

    • TileMatrixSet.lnglat(x, y): Transforms a point from TMS CRS (x, y) to geographic longitude and latitude.
    • TileMatrixSet.xy(lng, lat): Transforms geographic longitude and latitude coordinates to TMS CRS (x, y).
    • TileMatrixSet.ul(Tile): Returns the upper-left coordinates of a tile in the geographic CRS.
    • TileMatrixSet.lr(Tile): Returns the lower-right coordinates of a tile in the geographic CRS.
    • TileMatrixSet.bounds(Tile): Returns the bounding box of a tile in the geographic CRS.
    • TileMatrixSet.bbox: Returns the entire TMS bounding box in the geographic CRS.
  10. Get tile bounds in different projections

    main

    Once you have a TileMatrixSet instance, you can retrieve the spatial bounds of a specific tile using morecantile.Tile(x, y, z).

    • Use tms.xy_bounds(tile) to get bounds in the TMS's native coordinate reference system (CRS).
    • Use tms.bounds(tile) to get bounds in Geographic CRS (typically Lat/Lon WGS84).
    import morecantile
    
    tms = morecantile.tms.get("WebMercatorQuad")
    tile = morecantile.Tile(10, 10, 4)
    
    # Bounds in input projection (e.g., EPSG:3857)
    xy_bounds = tms.xy_bounds(tile)
    
    # Bounds in LatLon (WGS84)
    latlon_bounds = tms.bounds(tile)
  11. Find a tile for a given coordinate

    main

    To find which tile covers a specific geographic location, use tms.tile(lon, lat, zoom) or tms.xy(x, y) to convert coordinates to the TMS's native CRS.

    • tms.tile(lon, lat, zoom): Returns a Tile object.
    • tms.xy(x, y): Returns the (x, y) coordinates in the TMS's native CRS.
    import morecantile
    
    tms = morecantile.tms.get("WebMercatorQuad")
    
    # Find tile from Lat/Lon
    tile = tms.tile(159.31, -42, 4)
    
    # Get native XY coordinates from Lat/Lon
    x, y = tms.xy(159.31, -42)