Skip to content

Allow indexing by tile #30

@ianhi

Description

@ianhi

Nice to provide indexing as if you input mercator tiles into https://dudewheresmytile.mattnucc.com/?tab=tile then did .sel on the bbox returned from there.

e.g. with below code you can do:

ds.tile("314/547/10")

and it will sel the correct bbox for you.

from typing import overload

import mercantile
import xarray as xr


@xr.register_dataset_accessor("tile")
@xr.register_dataarray_accessor("tile")
class TileAccessor:
    def __init__(self, xarray_obj):
        self._ds = xarray_obj

    def mbbox(self, bbox: mercantile.LngLatBbox) -> xr.Dataset:
        return self._ds.sel(
            {
                ds.cf["longitude"].name: slice(bbox.west, bbox.east),
                ds.cf["latitude"].name: slice(bbox.south, bbox.north),
            }
        )

    @overload
    def __call__(self, tile: str) -> xr.Dataset: ...

    def __call__(self, X: int, Y: int = None, zoom: int = None) -> xr.Dataset:
        """
        Slice the bbox associated with the tile.
        Valid inputs:
        "lat/lon/zoom"
        "lat,lon,zoom"
        lat, lon, zoom (as integers)
        not sure how to do params properly for this overload.
        """
        # no safety checks! be good plz :)

        if isinstance(X, str):
            bbox = mercantile.bounds(tuple(map(int, X.replace(",", "/").split("/"))))
        else:
            bbox = mercantile.bounds(X, Y, zoom)
        return self.mbbox(bbox)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions