Skip to content

stac module

PlanetaryComputerEndpoint

Bases: TitilerEndpoint

This class contains the methods for the Microsoft Planetary Computer endpoint.

Source code in leafmap/stac.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
class PlanetaryComputerEndpoint(TitilerEndpoint):
    """This class contains the methods for the Microsoft Planetary Computer endpoint."""

    def __init__(
        self,
        endpoint: Optional[str] = "https://planetarycomputer.microsoft.com/api/data/v1",
        name: Optional[str] = "item",
        TileMatrixSetId: Optional[str] = "WebMercatorQuad",
    ):
        """Initialize the PlanetaryComputerEndpoint object.

        Args:
            endpoint (str, optional): The endpoint of the titiler server. Defaults to "https://planetarycomputer.microsoft.com/api/data/v1".
            name (str, optional): The name to be used in the file path. Defaults to "item".
            TileMatrixSetId (str, optional): The TileMatrixSetId to be used in the file path. Defaults to "WebMercatorQuad".
        """
        super().__init__(endpoint, name, TileMatrixSetId)

    def url_for_stac_collection(self):
        return f"{self.endpoint}/collection/{self.TileMatrixSetId}/tilejson.json"

    def url_for_collection_assets(self):
        return f"{self.endpoint}/collection/assets"

    def url_for_collection_bounds(self):
        return f"{self.endpoint}/collection/bounds"

    def url_for_collection_info(self):
        return f"{self.endpoint}/collection/info"

    def url_for_collection_info_geojson(self):
        return f"{self.endpoint}/collection/info.geojson"

    def url_for_collection_pixel_value(self, lon, lat):
        return f"{self.endpoint}/collection/point/{lon},{lat}"

    def url_for_collection_wmts(self):
        return f"{self.endpoint}/collection/{self.TileMatrixSetId}/WMTSCapabilities.xml"

    def url_for_collection_lat_lon_assets(self, lng, lat):
        return f"{self.endpoint}/collection/{lng},{lat}/assets"

    def url_for_collection_bbox_assets(self, minx, miny, maxx, maxy):
        return f"{self.endpoint}/collection/{minx},{miny},{maxx},{maxy}/assets"

    def url_for_stac_mosaic(self, searchid):
        return f"{self.endpoint}/mosaic/{searchid}/{self.TileMatrixSetId}/tilejson.json"

    def url_for_mosaic_info(self, searchid):
        return f"{self.endpoint}/mosaic/{searchid}/info"

    def url_for_mosaic_lat_lon_assets(self, searchid, lon, lat):
        return f"{self.endpoint}/mosaic/{searchid}/{lon},{lat}/assets"

__init__(endpoint='https://planetarycomputer.microsoft.com/api/data/v1', name='item', TileMatrixSetId='WebMercatorQuad')

Initialize the PlanetaryComputerEndpoint object.

Parameters:

Name Type Description Default
endpoint str

The endpoint of the titiler server. Defaults to "https://planetarycomputer.microsoft.com/api/data/v1".

'https://planetarycomputer.microsoft.com/api/data/v1'
name str

The name to be used in the file path. Defaults to "item".

'item'
TileMatrixSetId str

The TileMatrixSetId to be used in the file path. Defaults to "WebMercatorQuad".

'WebMercatorQuad'
Source code in leafmap/stac.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def __init__(
    self,
    endpoint: Optional[str] = "https://planetarycomputer.microsoft.com/api/data/v1",
    name: Optional[str] = "item",
    TileMatrixSetId: Optional[str] = "WebMercatorQuad",
):
    """Initialize the PlanetaryComputerEndpoint object.

    Args:
        endpoint (str, optional): The endpoint of the titiler server. Defaults to "https://planetarycomputer.microsoft.com/api/data/v1".
        name (str, optional): The name to be used in the file path. Defaults to "item".
        TileMatrixSetId (str, optional): The TileMatrixSetId to be used in the file path. Defaults to "WebMercatorQuad".
    """
    super().__init__(endpoint, name, TileMatrixSetId)

TitilerCMREndpoint

This class contains the methods for the TiTiler CMR endpoint.

Source code in leafmap/stac.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
class TitilerCMREndpoint:
    """This class contains the methods for the TiTiler CMR endpoint."""

    def __init__(
        self,
        endpoint: Optional[str] = None,
        TileMatrixSetId: Optional[str] = "WebMercatorQuad",
    ):
        """Initialize the TitilerCMREndpoint object.

        Args:
            endpoint (str, optional): The TiTiler CMR endpoint URL.
                Defaults to "https://staging.openveda.cloud/api/titiler-cmr".
            TileMatrixSetId (str, optional): The TileMatrixSetId. Defaults to "WebMercatorQuad".
        """
        if endpoint is None:
            endpoint = os.environ.get(
                "TITILER_CMR_ENDPOINT",
                "https://staging.openveda.cloud/api/titiler-cmr",
            )
        self.endpoint = endpoint
        self.TileMatrixSetId = TileMatrixSetId

    def url_for_tilejson(self):
        """Get the URL for the TileJSON endpoint.

        Returns:
            str: The TileJSON endpoint URL.
        """
        return f"{self.endpoint}/{self.TileMatrixSetId}/tilejson.json"

    def url_for_timeseries_tilejson(self):
        """Get the URL for the time series TileJSON endpoint.

        Returns:
            str: The time series TileJSON endpoint URL.
        """
        return f"{self.endpoint}/timeseries/{self.TileMatrixSetId}/tilejson.json"

    def url_for_timeseries_gif(self, bbox, width=512, height=512):
        """Get the URL for the time series animated GIF endpoint.

        Args:
            bbox (list | tuple): Bounding box as [minx, miny, maxx, maxy].
            width (int, optional): Width of the GIF in pixels. Defaults to 512.
            height (int, optional): Height of the GIF in pixels. Defaults to 512.

        Returns:
            str: The time series GIF endpoint URL.
        """
        minx, miny, maxx, maxy = bbox
        return f"{self.endpoint}/timeseries/bbox/{minx},{miny},{maxx},{maxy}/{width}x{height}.gif"

    def url_for_statistics(self):
        """Get the URL for the statistics endpoint.

        Returns:
            str: The statistics endpoint URL.
        """
        return f"{self.endpoint}/statistics"

    def url_for_timeseries_statistics(self):
        """Get the URL for the time series statistics endpoint.

        Returns:
            str: The time series statistics endpoint URL.
        """
        return f"{self.endpoint}/timeseries/statistics"

    def url_for_timeseries(self):
        """Get the URL for the time series endpoint.

        Returns:
            str: The time series endpoint URL.
        """
        return f"{self.endpoint}/timeseries"

__init__(endpoint=None, TileMatrixSetId='WebMercatorQuad')

Initialize the TitilerCMREndpoint object.

Parameters:

Name Type Description Default
endpoint str

The TiTiler CMR endpoint URL. Defaults to "https://staging.openveda.cloud/api/titiler-cmr".

None
TileMatrixSetId str

The TileMatrixSetId. Defaults to "WebMercatorQuad".

'WebMercatorQuad'
Source code in leafmap/stac.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def __init__(
    self,
    endpoint: Optional[str] = None,
    TileMatrixSetId: Optional[str] = "WebMercatorQuad",
):
    """Initialize the TitilerCMREndpoint object.

    Args:
        endpoint (str, optional): The TiTiler CMR endpoint URL.
            Defaults to "https://staging.openveda.cloud/api/titiler-cmr".
        TileMatrixSetId (str, optional): The TileMatrixSetId. Defaults to "WebMercatorQuad".
    """
    if endpoint is None:
        endpoint = os.environ.get(
            "TITILER_CMR_ENDPOINT",
            "https://staging.openveda.cloud/api/titiler-cmr",
        )
    self.endpoint = endpoint
    self.TileMatrixSetId = TileMatrixSetId

url_for_statistics()

Get the URL for the statistics endpoint.

Returns:

Name Type Description
str

The statistics endpoint URL.

Source code in leafmap/stac.py
170
171
172
173
174
175
176
def url_for_statistics(self):
    """Get the URL for the statistics endpoint.

    Returns:
        str: The statistics endpoint URL.
    """
    return f"{self.endpoint}/statistics"

url_for_tilejson()

Get the URL for the TileJSON endpoint.

Returns:

Name Type Description
str

The TileJSON endpoint URL.

Source code in leafmap/stac.py
140
141
142
143
144
145
146
def url_for_tilejson(self):
    """Get the URL for the TileJSON endpoint.

    Returns:
        str: The TileJSON endpoint URL.
    """
    return f"{self.endpoint}/{self.TileMatrixSetId}/tilejson.json"

url_for_timeseries()

Get the URL for the time series endpoint.

Returns:

Name Type Description
str

The time series endpoint URL.

Source code in leafmap/stac.py
186
187
188
189
190
191
192
def url_for_timeseries(self):
    """Get the URL for the time series endpoint.

    Returns:
        str: The time series endpoint URL.
    """
    return f"{self.endpoint}/timeseries"

url_for_timeseries_gif(bbox, width=512, height=512)

Get the URL for the time series animated GIF endpoint.

Parameters:

Name Type Description Default
bbox list | tuple

Bounding box as [minx, miny, maxx, maxy].

required
width int

Width of the GIF in pixels. Defaults to 512.

512
height int

Height of the GIF in pixels. Defaults to 512.

512

Returns:

Name Type Description
str

The time series GIF endpoint URL.

Source code in leafmap/stac.py
156
157
158
159
160
161
162
163
164
165
166
167
168
def url_for_timeseries_gif(self, bbox, width=512, height=512):
    """Get the URL for the time series animated GIF endpoint.

    Args:
        bbox (list | tuple): Bounding box as [minx, miny, maxx, maxy].
        width (int, optional): Width of the GIF in pixels. Defaults to 512.
        height (int, optional): Height of the GIF in pixels. Defaults to 512.

    Returns:
        str: The time series GIF endpoint URL.
    """
    minx, miny, maxx, maxy = bbox
    return f"{self.endpoint}/timeseries/bbox/{minx},{miny},{maxx},{maxy}/{width}x{height}.gif"

url_for_timeseries_statistics()

Get the URL for the time series statistics endpoint.

Returns:

Name Type Description
str

The time series statistics endpoint URL.

Source code in leafmap/stac.py
178
179
180
181
182
183
184
def url_for_timeseries_statistics(self):
    """Get the URL for the time series statistics endpoint.

    Returns:
        str: The time series statistics endpoint URL.
    """
    return f"{self.endpoint}/timeseries/statistics"

url_for_timeseries_tilejson()

Get the URL for the time series TileJSON endpoint.

Returns:

Name Type Description
str

The time series TileJSON endpoint URL.

Source code in leafmap/stac.py
148
149
150
151
152
153
154
def url_for_timeseries_tilejson(self):
    """Get the URL for the time series TileJSON endpoint.

    Returns:
        str: The time series TileJSON endpoint URL.
    """
    return f"{self.endpoint}/timeseries/{self.TileMatrixSetId}/tilejson.json"

TitilerEndpoint

This class contains the methods for the titiler endpoint.

Source code in leafmap/stac.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class TitilerEndpoint:
    """This class contains the methods for the titiler endpoint."""

    def __init__(
        self,
        endpoint: Optional[str] = None,
        name: Optional[str] = "stac",
        TileMatrixSetId: Optional[str] = "WebMercatorQuad",
    ):
        """Initialize the TiTilerEndpoint object.

        Args:
            endpoint (str, optional): The endpoint of the titiler server. Defaults to "https://giswqs-titiler-endpoint.hf.space".
            name (str, optional): The name to be used in the file path. Defaults to "stac".
            TileMatrixSetId (str, optional): The TileMatrixSetId to be used in the file path. Defaults to "WebMercatorQuad".
        """
        self.endpoint = endpoint
        self.name = name
        self.TileMatrixSetId = TileMatrixSetId

    def url_for_stac_item(self):
        return f"{self.endpoint}/{self.name}/{self.TileMatrixSetId}/tilejson.json"

    def url_for_stac_assets(self):
        return f"{self.endpoint}/{self.name}/assets"

    def url_for_stac_bounds(self):
        return f"{self.endpoint}/{self.name}/info.geojson"

    def url_for_stac_info(self):
        return f"{self.endpoint}/{self.name}/info"

    def url_for_stac_info_geojson(self):
        return f"{self.endpoint}/{self.name}/info.geojson"

    def url_for_stac_statistics(self):
        return f"{self.endpoint}/{self.name}/statistics"

    def url_for_stac_pixel_value(self, lon, lat):
        return f"{self.endpoint}/{self.name}/point/{lon},{lat}"

    def url_for_stac_wmts(self):
        return (
            f"{self.endpoint}/{self.name}/{self.TileMatrixSetId}/WMTSCapabilities.xml"
        )

__init__(endpoint=None, name='stac', TileMatrixSetId='WebMercatorQuad')

Initialize the TiTilerEndpoint object.

Parameters:

Name Type Description Default
endpoint str

The endpoint of the titiler server. Defaults to "https://giswqs-titiler-endpoint.hf.space".

None
name str

The name to be used in the file path. Defaults to "stac".

'stac'
TileMatrixSetId str

The TileMatrixSetId to be used in the file path. Defaults to "WebMercatorQuad".

'WebMercatorQuad'
Source code in leafmap/stac.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def __init__(
    self,
    endpoint: Optional[str] = None,
    name: Optional[str] = "stac",
    TileMatrixSetId: Optional[str] = "WebMercatorQuad",
):
    """Initialize the TiTilerEndpoint object.

    Args:
        endpoint (str, optional): The endpoint of the titiler server. Defaults to "https://giswqs-titiler-endpoint.hf.space".
        name (str, optional): The name to be used in the file path. Defaults to "stac".
        TileMatrixSetId (str, optional): The TileMatrixSetId to be used in the file path. Defaults to "WebMercatorQuad".
    """
    self.endpoint = endpoint
    self.name = name
    self.TileMatrixSetId = TileMatrixSetId

check_titiler_cmr_endpoint(titiler_cmr_endpoint=None)

Returns the TiTiler CMR endpoint.

Parameters:

Name Type Description Default
titiler_cmr_endpoint str

The TiTiler CMR endpoint URL. Defaults to None.

None

Returns:

Name Type Description
TitilerCMREndpoint TitilerCMREndpoint

The TiTiler CMR endpoint object.

Source code in leafmap/stac.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def check_titiler_cmr_endpoint(
    titiler_cmr_endpoint: Optional[str] = None,
) -> TitilerCMREndpoint:
    """Returns the TiTiler CMR endpoint.

    Args:
        titiler_cmr_endpoint (str, optional): The TiTiler CMR endpoint URL. Defaults to None.

    Returns:
        TitilerCMREndpoint: The TiTiler CMR endpoint object.
    """
    if titiler_cmr_endpoint is None:
        titiler_cmr_endpoint = os.environ.get(
            "TITILER_CMR_ENDPOINT",
            "https://staging.openveda.cloud/api/titiler-cmr",
        )

    if isinstance(titiler_cmr_endpoint, str):
        return TitilerCMREndpoint(endpoint=titiler_cmr_endpoint)
    elif isinstance(titiler_cmr_endpoint, TitilerCMREndpoint):
        return titiler_cmr_endpoint
    else:
        return TitilerCMREndpoint()

check_titiler_endpoint(titiler_endpoint=None)

Returns the default titiler endpoint.

Returns:

Type Description
Any

The titiler endpoint.

Source code in leafmap/stac.py
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
def check_titiler_endpoint(titiler_endpoint: Optional[str] = None) -> Any:
    """Returns the default titiler endpoint.

    Returns:
        The titiler endpoint.
    """
    if (
        titiler_endpoint is not None
        and isinstance(titiler_endpoint, str)
        and titiler_endpoint.lower() == "local"
    ):
        titiler_endpoint = run_titiler(show_logs=False)
    elif titiler_endpoint is None:
        if os.environ.get("TITILER_ENDPOINT") is not None:
            titiler_endpoint = os.environ.get("TITILER_ENDPOINT")

            if titiler_endpoint == "planetary-computer":
                titiler_endpoint = PlanetaryComputerEndpoint()
        else:
            titiler_endpoint = "https://giswqs-titiler-endpoint.hf.space"
    elif isinstance(titiler_endpoint, str) and titiler_endpoint in [
        "planetary-computer",
        "pc",
    ]:
        titiler_endpoint = PlanetaryComputerEndpoint()
    # If it's already an endpoint object, just return it as-is

    return titiler_endpoint

cmr_animated_gif(concept_id, datetime, bbox, width=512, height=512, step='P1D', temporal_mode='point', backend='rasterio', variable=None, bands=None, bands_regex=None, expression=None, rescale=None, colormap_name=None, color_formula=None, fps=1, output=None, titiler_cmr_endpoint=None, **kwargs)

Generate animated GIF for time series from TiTiler CMR.

Parameters:

Name Type Description Default
concept_id str

NASA CMR collection concept ID (e.g., 'C2036881735-POCLOUD').

required
datetime str

RFC3339 datetime range (e.g., '2024-01-01/2024-01-31').

required
bbox list | tuple

Bounding box as [minx, miny, maxx, maxy].

required
width int

Width of the GIF in pixels. Defaults to 512.

512
height int

Height of the GIF in pixels. Defaults to 512.

512
step str

ISO 8601 duration for time steps (e.g., 'P1D' for 1 day, 'P1M' for 1 month). Defaults to 'P1D'.

'P1D'
temporal_mode str

Temporal mode - 'point' or 'range'. Defaults to 'point'.

'point'
backend str

Backend to use - 'rasterio' for COGs or 'xarray' for NetCDF/Zarr. Defaults to 'rasterio'.

'rasterio'
variable str

Variable name for xarray backend datasets.

None
bands str | list

Band name(s) for rasterio backend.

None
bands_regex str

Regex pattern for selecting bands (e.g., 'B[0-9][]').

None
expression str

Band math expression (e.g., '(B05-B04)/(B05+B04)').

None
rescale str | list

Min/max values for rescaling (e.g., '270,305' or [[270, 305]]).

None
colormap_name str

Name of colormap (e.g., 'thermal', 'viridis').

None
color_formula str

Color formula (e.g., 'Gamma RGB 3.5 Saturation 1.7').

None
fps int

Frames per second for the GIF. Defaults to 1.

1
output str

Output file path. If None, returns the URL.

None
titiler_cmr_endpoint str

TiTiler CMR endpoint URL.

None
**kwargs

Additional parameters.

{}

Returns:

Name Type Description
str str

The GIF URL or output file path.

Source code in leafmap/stac.py
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
def cmr_animated_gif(
    concept_id: str,
    datetime: str,
    bbox: Union[List[float], Tuple[float, float, float, float]],
    width: int = 512,
    height: int = 512,
    step: str = "P1D",
    temporal_mode: str = "point",
    backend: str = "rasterio",
    variable: Optional[str] = None,
    bands: Optional[Union[str, List[str]]] = None,
    bands_regex: Optional[str] = None,
    expression: Optional[str] = None,
    rescale: Optional[Union[str, List]] = None,
    colormap_name: Optional[str] = None,
    color_formula: Optional[str] = None,
    fps: int = 1,
    output: Optional[str] = None,
    titiler_cmr_endpoint: Optional[str] = None,
    **kwargs,
) -> str:
    """Generate animated GIF for time series from TiTiler CMR.

    Args:
        concept_id (str): NASA CMR collection concept ID (e.g., 'C2036881735-POCLOUD').
        datetime (str): RFC3339 datetime range (e.g., '2024-01-01/2024-01-31').
        bbox (list | tuple): Bounding box as [minx, miny, maxx, maxy].
        width (int, optional): Width of the GIF in pixels. Defaults to 512.
        height (int, optional): Height of the GIF in pixels. Defaults to 512.
        step (str, optional): ISO 8601 duration for time steps (e.g., 'P1D' for 1 day,
            'P1M' for 1 month). Defaults to 'P1D'.
        temporal_mode (str, optional): Temporal mode - 'point' or 'range'. Defaults to 'point'.
        backend (str, optional): Backend to use - 'rasterio' for COGs or 'xarray' for NetCDF/Zarr.
            Defaults to 'rasterio'.
        variable (str, optional): Variable name for xarray backend datasets.
        bands (str | list, optional): Band name(s) for rasterio backend.
        bands_regex (str, optional): Regex pattern for selecting bands (e.g., 'B[0-9][0-9]').
        expression (str, optional): Band math expression (e.g., '(B05-B04)/(B05+B04)').
        rescale (str | list, optional): Min/max values for rescaling (e.g., '270,305' or [[270, 305]]).
        colormap_name (str, optional): Name of colormap (e.g., 'thermal', 'viridis').
        color_formula (str, optional): Color formula (e.g., 'Gamma RGB 3.5 Saturation 1.7').
        fps (int, optional): Frames per second for the GIF. Defaults to 1.
        output (str, optional): Output file path. If None, returns the URL.
        titiler_cmr_endpoint (str, optional): TiTiler CMR endpoint URL.
        **kwargs: Additional parameters.

    Returns:
        str: The GIF URL or output file path.
    """
    if os.environ.get("USE_MKDOCS") is not None:
        return None

    endpoint = check_titiler_cmr_endpoint(titiler_cmr_endpoint)

    params = {
        "concept_id": concept_id,
        "datetime": datetime,
        "step": step,
        "temporal_mode": temporal_mode,
        "backend": backend,
        "fps": fps,
    }

    if variable is not None:
        params["variable"] = variable

    if bands is not None:
        if isinstance(bands, list):
            # Pass bands as a list so requests encodes as bands=B04&bands=B03&bands=B02
            params["bands"] = bands
        else:
            params["bands"] = [bands]
    elif expression is not None:
        # Extract band names from expression (e.g., "(B05-B04)/(B05+B04)" -> ["B05", "B04"])
        # Band names typically match patterns like B01, B02, B8A, etc.
        band_pattern = r"\b(B[0-9][0-9A-Za-z]?)\b"
        extracted_bands = list(dict.fromkeys(re.findall(band_pattern, expression)))
        if extracted_bands:
            params["bands"] = extracted_bands

    if bands_regex is not None:
        params["bands_regex"] = bands_regex

    if expression is not None:
        params["expression"] = expression

    if rescale is not None:
        if isinstance(rescale, list):
            if isinstance(rescale[0], list):
                params["rescale"] = ",".join([f"{r[0]},{r[1]}" for r in rescale])
            else:
                params["rescale"] = ",".join([str(r) for r in rescale])
        else:
            params["rescale"] = rescale

    if colormap_name is not None:
        params["colormap_name"] = colormap_name

    if color_formula is not None:
        params["color_formula"] = color_formula

    params.update(kwargs)

    url = endpoint.url_for_timeseries_gif(bbox, width, height)

    if output is not None:
        try:
            response = requests.get(url, params=params, timeout=120)
            response.raise_for_status()
            with open(output, "wb") as f:
                f.write(response.content)
            return output
        except Exception as e:
            print(f"Error downloading GIF from TiTiler CMR: {e}")
            return None
    else:
        # Return the full URL with parameters
        from urllib.parse import urlencode

        return f"{url}?{urlencode(params)}"

cmr_bounds(concept_id, datetime=None, backend='rasterio', variable=None, titiler_cmr_endpoint=None, **kwargs)

Get bounding box from TiTiler CMR TileJSON.

Parameters:

Name Type Description Default
concept_id str

NASA CMR collection concept ID (e.g., 'C2036881735-POCLOUD').

required
datetime str

RFC3339 datetime or range (e.g., '2024-01-15' or '2024-01-01/2024-01-31').

None
backend str

Backend to use - 'rasterio' for COGs or 'xarray' for NetCDF/Zarr. Defaults to 'rasterio'.

'rasterio'
variable str

Variable name for xarray backend datasets.

None
titiler_cmr_endpoint str

TiTiler CMR endpoint URL.

None
**kwargs

Additional parameters.

{}

Returns:

Name Type Description
list List[float]

Bounding box as [minx, miny, maxx, maxy].

Source code in leafmap/stac.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
def cmr_bounds(
    concept_id: str,
    datetime: Optional[str] = None,
    backend: str = "rasterio",
    variable: Optional[str] = None,
    titiler_cmr_endpoint: Optional[str] = None,
    **kwargs,
) -> List[float]:
    """Get bounding box from TiTiler CMR TileJSON.

    Args:
        concept_id (str): NASA CMR collection concept ID (e.g., 'C2036881735-POCLOUD').
        datetime (str, optional): RFC3339 datetime or range (e.g., '2024-01-15' or '2024-01-01/2024-01-31').
        backend (str, optional): Backend to use - 'rasterio' for COGs or 'xarray' for NetCDF/Zarr.
            Defaults to 'rasterio'.
        variable (str, optional): Variable name for xarray backend datasets.
        titiler_cmr_endpoint (str, optional): TiTiler CMR endpoint URL.
        **kwargs: Additional parameters.

    Returns:
        list: Bounding box as [minx, miny, maxx, maxy].
    """
    tilejson = cmr_tilejson(
        concept_id=concept_id,
        datetime=datetime,
        backend=backend,
        variable=variable,
        titiler_cmr_endpoint=titiler_cmr_endpoint,
        **kwargs,
    )

    if tilejson is None or "bounds" not in tilejson:
        return None

    return tilejson["bounds"]

cmr_center(concept_id, datetime=None, backend='rasterio', variable=None, titiler_cmr_endpoint=None, **kwargs)

Get center coordinates from TiTiler CMR TileJSON.

Parameters:

Name Type Description Default
concept_id str

NASA CMR collection concept ID (e.g., 'C2036881735-POCLOUD').

required
datetime str

RFC3339 datetime or range (e.g., '2024-01-15' or '2024-01-01/2024-01-31').

None
backend str

Backend to use - 'rasterio' for COGs or 'xarray' for NetCDF/Zarr. Defaults to 'rasterio'.

'rasterio'
variable str

Variable name for xarray backend datasets.

None
titiler_cmr_endpoint str

TiTiler CMR endpoint URL.

None
**kwargs

Additional parameters.

{}

Returns:

Name Type Description
tuple Tuple[float, float]

Center coordinates as (longitude, latitude).

Source code in leafmap/stac.py
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
def cmr_center(
    concept_id: str,
    datetime: Optional[str] = None,
    backend: str = "rasterio",
    variable: Optional[str] = None,
    titiler_cmr_endpoint: Optional[str] = None,
    **kwargs,
) -> Tuple[float, float]:
    """Get center coordinates from TiTiler CMR TileJSON.

    Args:
        concept_id (str): NASA CMR collection concept ID (e.g., 'C2036881735-POCLOUD').
        datetime (str, optional): RFC3339 datetime or range (e.g., '2024-01-15' or '2024-01-01/2024-01-31').
        backend (str, optional): Backend to use - 'rasterio' for COGs or 'xarray' for NetCDF/Zarr.
            Defaults to 'rasterio'.
        variable (str, optional): Variable name for xarray backend datasets.
        titiler_cmr_endpoint (str, optional): TiTiler CMR endpoint URL.
        **kwargs: Additional parameters.

    Returns:
        tuple: Center coordinates as (longitude, latitude).
    """
    tilejson = cmr_tilejson(
        concept_id=concept_id,
        datetime=datetime,
        backend=backend,
        variable=variable,
        titiler_cmr_endpoint=titiler_cmr_endpoint,
        **kwargs,
    )

    if tilejson is None or "center" not in tilejson:
        bounds = cmr_bounds(
            concept_id=concept_id,
            datetime=datetime,
            backend=backend,
            variable=variable,
            titiler_cmr_endpoint=titiler_cmr_endpoint,
            **kwargs,
        )
        if bounds is not None:
            return ((bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2)
        return (None, None)

    center = tilejson["center"]
    return (center[0], center[1])

cmr_statistics(concept_id, datetime=None, geojson=None, backend='rasterio', variable=None, bands=None, titiler_cmr_endpoint=None, **kwargs)

Calculate statistics for an AOI from TiTiler CMR.

Parameters:

Name Type Description Default
concept_id str

NASA CMR collection concept ID (e.g., 'C2036881735-POCLOUD').

required
datetime str

RFC3339 datetime or range (e.g., '2024-01-15' or '2024-01-01/2024-01-31').

None
geojson dict | str

GeoJSON geometry or file path for the AOI.

None
backend str

Backend to use - 'rasterio' for COGs or 'xarray' for NetCDF/Zarr. Defaults to 'rasterio'.

'rasterio'
variable str

Variable name for xarray backend datasets.

None
bands str | list

Band name(s) for rasterio backend.

None
titiler_cmr_endpoint str

TiTiler CMR endpoint URL.

None
**kwargs

Additional parameters.

{}

Returns:

Name Type Description
dict Dict

Statistics for the AOI.

Source code in leafmap/stac.py
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
def cmr_statistics(
    concept_id: str,
    datetime: Optional[str] = None,
    geojson: Optional[Union[Dict, str]] = None,
    backend: str = "rasterio",
    variable: Optional[str] = None,
    bands: Optional[Union[str, List[str]]] = None,
    titiler_cmr_endpoint: Optional[str] = None,
    **kwargs,
) -> Dict:
    """Calculate statistics for an AOI from TiTiler CMR.

    Args:
        concept_id (str): NASA CMR collection concept ID (e.g., 'C2036881735-POCLOUD').
        datetime (str, optional): RFC3339 datetime or range (e.g., '2024-01-15' or '2024-01-01/2024-01-31').
        geojson (dict | str, optional): GeoJSON geometry or file path for the AOI.
        backend (str, optional): Backend to use - 'rasterio' for COGs or 'xarray' for NetCDF/Zarr.
            Defaults to 'rasterio'.
        variable (str, optional): Variable name for xarray backend datasets.
        bands (str | list, optional): Band name(s) for rasterio backend.
        titiler_cmr_endpoint (str, optional): TiTiler CMR endpoint URL.
        **kwargs: Additional parameters.

    Returns:
        dict: Statistics for the AOI.
    """
    import json

    if os.environ.get("USE_MKDOCS") is not None:
        return None

    endpoint = check_titiler_cmr_endpoint(titiler_cmr_endpoint)

    params = {"concept_id": concept_id, "backend": backend}

    if datetime is not None:
        params["datetime"] = datetime

    if variable is not None:
        params["variable"] = variable

    if bands is not None:
        if isinstance(bands, list):
            # Pass bands as a list so requests encodes as bands=B04&bands=B03&bands=B02
            params["bands"] = bands
        else:
            params["bands"] = [bands]

    params.update(kwargs)

    # Handle GeoJSON input
    if geojson is not None:
        if isinstance(geojson, str):
            if os.path.exists(geojson):
                with open(geojson, "r") as f:
                    geojson = json.load(f)
            else:
                geojson = json.loads(geojson)

        try:
            response = requests.post(
                endpoint.url_for_statistics(),
                params=params,
                json=geojson,
                timeout=60,
            )
            response.raise_for_status()
            return response.json()
        except Exception as e:
            print(f"Error fetching statistics from TiTiler CMR: {e}")
            return None
    else:
        try:
            response = requests.get(
                endpoint.url_for_statistics(), params=params, timeout=60
            )
            response.raise_for_status()
            return response.json()
        except Exception as e:
            print(f"Error fetching statistics from TiTiler CMR: {e}")
            return None

cmr_tile(concept_id, datetime=None, backend='rasterio', variable=None, bands=None, bands_regex=None, expression=None, rescale=None, colormap_name=None, color_formula=None, titiler_cmr_endpoint=None, **kwargs)

Get tile URL from TiTiler CMR.

Parameters:

Name Type Description Default
concept_id str

NASA CMR collection concept ID (e.g., 'C2036881735-POCLOUD').

required
datetime str

RFC3339 datetime or range (e.g., '2024-01-15' or '2024-01-01/2024-01-31').

None
backend str

Backend to use - 'rasterio' for COGs or 'xarray' for NetCDF/Zarr. Defaults to 'rasterio'.

'rasterio'
variable str

Variable name for xarray backend datasets.

None
bands str | list

Band name(s) for rasterio backend.

None
bands_regex str

Regex pattern for selecting bands (e.g., 'B[0-9][]').

None
expression str

Band math expression (e.g., '(B05-B04)/(B05+B04)').

None
rescale str | list

Min/max values for rescaling (e.g., '270,305' or [[270, 305]]).

None
colormap_name str

Name of colormap (e.g., 'thermal', 'viridis').

None
color_formula str

Color formula (e.g., 'Gamma RGB 3.5 Saturation 1.7').

None
titiler_cmr_endpoint str

TiTiler CMR endpoint URL.

None
**kwargs

Additional parameters to pass to the TiTiler CMR endpoint.

{}

Returns:

Name Type Description
str str

The tile URL template.

Source code in leafmap/stac.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
def cmr_tile(
    concept_id: str,
    datetime: Optional[str] = None,
    backend: str = "rasterio",
    variable: Optional[str] = None,
    bands: Optional[Union[str, List[str]]] = None,
    bands_regex: Optional[str] = None,
    expression: Optional[str] = None,
    rescale: Optional[Union[str, List]] = None,
    colormap_name: Optional[str] = None,
    color_formula: Optional[str] = None,
    titiler_cmr_endpoint: Optional[str] = None,
    **kwargs,
) -> str:
    """Get tile URL from TiTiler CMR.

    Args:
        concept_id (str): NASA CMR collection concept ID (e.g., 'C2036881735-POCLOUD').
        datetime (str, optional): RFC3339 datetime or range (e.g., '2024-01-15' or '2024-01-01/2024-01-31').
        backend (str, optional): Backend to use - 'rasterio' for COGs or 'xarray' for NetCDF/Zarr.
            Defaults to 'rasterio'.
        variable (str, optional): Variable name for xarray backend datasets.
        bands (str | list, optional): Band name(s) for rasterio backend.
        bands_regex (str, optional): Regex pattern for selecting bands (e.g., 'B[0-9][0-9]').
        expression (str, optional): Band math expression (e.g., '(B05-B04)/(B05+B04)').
        rescale (str | list, optional): Min/max values for rescaling (e.g., '270,305' or [[270, 305]]).
        colormap_name (str, optional): Name of colormap (e.g., 'thermal', 'viridis').
        color_formula (str, optional): Color formula (e.g., 'Gamma RGB 3.5 Saturation 1.7').
        titiler_cmr_endpoint (str, optional): TiTiler CMR endpoint URL.
        **kwargs: Additional parameters to pass to the TiTiler CMR endpoint.

    Returns:
        str: The tile URL template.
    """
    tilejson = cmr_tilejson(
        concept_id=concept_id,
        datetime=datetime,
        backend=backend,
        variable=variable,
        bands=bands,
        bands_regex=bands_regex,
        expression=expression,
        rescale=rescale,
        colormap_name=colormap_name,
        color_formula=color_formula,
        titiler_cmr_endpoint=titiler_cmr_endpoint,
        **kwargs,
    )

    if tilejson is None or "tiles" not in tilejson:
        return None

    return tilejson["tiles"][0]

cmr_tilejson(concept_id, datetime=None, backend='rasterio', variable=None, bands=None, bands_regex=None, expression=None, rescale=None, colormap_name=None, color_formula=None, titiler_cmr_endpoint=None, **kwargs)

Fetch TileJSON metadata from TiTiler CMR.

Parameters:

Name Type Description Default
concept_id str

NASA CMR collection concept ID (e.g., 'C2036881735-POCLOUD').

required
datetime str

RFC3339 datetime or range (e.g., '2024-01-15' or '2024-01-01/2024-01-31').

None
backend str

Backend to use - 'rasterio' for COGs or 'xarray' for NetCDF/Zarr. Defaults to 'rasterio'.

'rasterio'
variable str

Variable name for xarray backend datasets.

None
bands str | list

Band name(s) for rasterio backend.

None
bands_regex str

Regex pattern for selecting bands (e.g., 'B[0-9][]').

None
expression str

Band math expression (e.g., '(B05-B04)/(B05+B04)').

None
rescale str | list

Min/max values for rescaling (e.g., '270,305' or [[270, 305]]).

None
colormap_name str

Name of colormap (e.g., 'thermal', 'viridis').

None
color_formula str

Color formula (e.g., 'Gamma RGB 3.5 Saturation 1.7').

None
titiler_cmr_endpoint str

TiTiler CMR endpoint URL.

None
**kwargs

Additional parameters to pass to the TiTiler CMR endpoint.

{}

Returns:

Name Type Description
dict Dict

TileJSON metadata dict with tiles, bounds, center, minzoom, maxzoom.

Source code in leafmap/stac.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
def cmr_tilejson(
    concept_id: str,
    datetime: Optional[str] = None,
    backend: str = "rasterio",
    variable: Optional[str] = None,
    bands: Optional[Union[str, List[str]]] = None,
    bands_regex: Optional[str] = None,
    expression: Optional[str] = None,
    rescale: Optional[Union[str, List]] = None,
    colormap_name: Optional[str] = None,
    color_formula: Optional[str] = None,
    titiler_cmr_endpoint: Optional[str] = None,
    **kwargs,
) -> Dict:
    """Fetch TileJSON metadata from TiTiler CMR.

    Args:
        concept_id (str): NASA CMR collection concept ID (e.g., 'C2036881735-POCLOUD').
        datetime (str, optional): RFC3339 datetime or range (e.g., '2024-01-15' or '2024-01-01/2024-01-31').
        backend (str, optional): Backend to use - 'rasterio' for COGs or 'xarray' for NetCDF/Zarr.
            Defaults to 'rasterio'.
        variable (str, optional): Variable name for xarray backend datasets.
        bands (str | list, optional): Band name(s) for rasterio backend.
        bands_regex (str, optional): Regex pattern for selecting bands (e.g., 'B[0-9][0-9]').
        expression (str, optional): Band math expression (e.g., '(B05-B04)/(B05+B04)').
        rescale (str | list, optional): Min/max values for rescaling (e.g., '270,305' or [[270, 305]]).
        colormap_name (str, optional): Name of colormap (e.g., 'thermal', 'viridis').
        color_formula (str, optional): Color formula (e.g., 'Gamma RGB 3.5 Saturation 1.7').
        titiler_cmr_endpoint (str, optional): TiTiler CMR endpoint URL.
        **kwargs: Additional parameters to pass to the TiTiler CMR endpoint.

    Returns:
        dict: TileJSON metadata dict with tiles, bounds, center, minzoom, maxzoom.
    """
    if os.environ.get("USE_MKDOCS") is not None:
        return None

    endpoint = check_titiler_cmr_endpoint(titiler_cmr_endpoint)

    params = {"concept_id": concept_id, "backend": backend}

    if datetime is not None:
        params["datetime"] = datetime

    if variable is not None:
        params["variable"] = variable

    if bands is not None:
        if isinstance(bands, list):
            # Pass bands as a list so requests encodes as bands=B04&bands=B03&bands=B02
            params["bands"] = bands
        else:
            params["bands"] = [bands]
    elif expression is not None:
        # Extract band names from expression (e.g., "(B05-B04)/(B05+B04)" -> ["B05", "B04"])
        # Band names typically match patterns like B01, B02, B8A, etc.
        band_pattern = r"\b(B[0-9][0-9A-Za-z]?)\b"
        extracted_bands = list(dict.fromkeys(re.findall(band_pattern, expression)))
        if extracted_bands:
            params["bands"] = extracted_bands

    if bands_regex is not None:
        params["bands_regex"] = bands_regex

    if expression is not None:
        params["expression"] = expression

    if rescale is not None:
        if isinstance(rescale, list):
            if isinstance(rescale[0], list):
                params["rescale"] = ",".join([f"{r[0]},{r[1]}" for r in rescale])
            else:
                params["rescale"] = ",".join([str(r) for r in rescale])
        else:
            params["rescale"] = rescale

    if colormap_name is not None:
        params["colormap_name"] = colormap_name

    if color_formula is not None:
        params["color_formula"] = color_formula

    params.update(kwargs)

    try:
        r = requests.get(endpoint.url_for_tilejson(), params=params, timeout=30).json()
        return r
    except Exception as e:
        print(f"Error fetching TileJSON from TiTiler CMR: {e}")
        return None

cmr_timeseries_tilejson(concept_id, datetime, step='P1D', temporal_mode='point', backend='rasterio', variable=None, bands=None, bands_regex=None, expression=None, rescale=None, colormap_name=None, color_formula=None, titiler_cmr_endpoint=None, **kwargs)

Get time series TileJSON dict from TiTiler CMR.

Parameters:

Name Type Description Default
concept_id str

NASA CMR collection concept ID (e.g., 'C2036881735-POCLOUD').

required
datetime str

RFC3339 datetime range (e.g., '2024-01-01/2024-01-31').

required
step str

ISO 8601 duration for time steps (e.g., 'P1D' for 1 day, 'P1M' for 1 month, 'P2W' for 2 weeks). Defaults to 'P1D'.

'P1D'
temporal_mode str

Temporal mode - 'point' or 'range'. Defaults to 'point'.

'point'
backend str

Backend to use - 'rasterio' for COGs or 'xarray' for NetCDF/Zarr. Defaults to 'rasterio'.

'rasterio'
variable str

Variable name for xarray backend datasets.

None
bands str | list

Band name(s) for rasterio backend.

None
bands_regex str

Regex pattern for selecting bands (e.g., 'B[0-9][]').

None
expression str

Band math expression (e.g., '(B05-B04)/(B05+B04)').

None
rescale str | list

Min/max values for rescaling (e.g., '270,305' or [[270, 305]]).

None
colormap_name str

Name of colormap (e.g., 'thermal', 'viridis').

None
color_formula str

Color formula (e.g., 'Gamma RGB 3.5 Saturation 1.7').

None
titiler_cmr_endpoint str

TiTiler CMR endpoint URL.

None
**kwargs

Additional parameters.

{}

Returns:

Name Type Description
dict Dict[str, Dict]

Dictionary mapping datetime strings to TileJSON metadata.

Source code in leafmap/stac.py
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
def cmr_timeseries_tilejson(
    concept_id: str,
    datetime: str,
    step: str = "P1D",
    temporal_mode: str = "point",
    backend: str = "rasterio",
    variable: Optional[str] = None,
    bands: Optional[Union[str, List[str]]] = None,
    bands_regex: Optional[str] = None,
    expression: Optional[str] = None,
    rescale: Optional[Union[str, List]] = None,
    colormap_name: Optional[str] = None,
    color_formula: Optional[str] = None,
    titiler_cmr_endpoint: Optional[str] = None,
    **kwargs,
) -> Dict[str, Dict]:
    """Get time series TileJSON dict from TiTiler CMR.

    Args:
        concept_id (str): NASA CMR collection concept ID (e.g., 'C2036881735-POCLOUD').
        datetime (str): RFC3339 datetime range (e.g., '2024-01-01/2024-01-31').
        step (str, optional): ISO 8601 duration for time steps (e.g., 'P1D' for 1 day,
            'P1M' for 1 month, 'P2W' for 2 weeks). Defaults to 'P1D'.
        temporal_mode (str, optional): Temporal mode - 'point' or 'range'. Defaults to 'point'.
        backend (str, optional): Backend to use - 'rasterio' for COGs or 'xarray' for NetCDF/Zarr.
            Defaults to 'rasterio'.
        variable (str, optional): Variable name for xarray backend datasets.
        bands (str | list, optional): Band name(s) for rasterio backend.
        bands_regex (str, optional): Regex pattern for selecting bands (e.g., 'B[0-9][0-9]').
        expression (str, optional): Band math expression (e.g., '(B05-B04)/(B05+B04)').
        rescale (str | list, optional): Min/max values for rescaling (e.g., '270,305' or [[270, 305]]).
        colormap_name (str, optional): Name of colormap (e.g., 'thermal', 'viridis').
        color_formula (str, optional): Color formula (e.g., 'Gamma RGB 3.5 Saturation 1.7').
        titiler_cmr_endpoint (str, optional): TiTiler CMR endpoint URL.
        **kwargs: Additional parameters.

    Returns:
        dict: Dictionary mapping datetime strings to TileJSON metadata.
    """
    if os.environ.get("USE_MKDOCS") is not None:
        return None

    endpoint = check_titiler_cmr_endpoint(titiler_cmr_endpoint)

    params = {
        "concept_id": concept_id,
        "datetime": datetime,
        "step": step,
        "temporal_mode": temporal_mode,
        "backend": backend,
    }

    if variable is not None:
        params["variable"] = variable

    if bands is not None:
        if isinstance(bands, list):
            # Pass bands as a list so requests encodes as bands=B04&bands=B03&bands=B02
            params["bands"] = bands
        else:
            params["bands"] = [bands]
    elif expression is not None:
        # Extract band names from expression (e.g., "(B05-B04)/(B05+B04)" -> ["B05", "B04"])
        # Band names typically match patterns like B01, B02, B8A, etc.
        band_pattern = r"\b(B[0-9][0-9A-Za-z]?)\b"
        extracted_bands = list(dict.fromkeys(re.findall(band_pattern, expression)))
        if extracted_bands:
            params["bands"] = extracted_bands

    if bands_regex is not None:
        params["bands_regex"] = bands_regex

    if expression is not None:
        params["expression"] = expression

    if rescale is not None:
        if isinstance(rescale, list):
            if isinstance(rescale[0], list):
                params["rescale"] = ",".join([f"{r[0]},{r[1]}" for r in rescale])
            else:
                params["rescale"] = ",".join([str(r) for r in rescale])
        else:
            params["rescale"] = rescale

    if colormap_name is not None:
        params["colormap_name"] = colormap_name

    if color_formula is not None:
        params["color_formula"] = color_formula

    params.update(kwargs)

    try:
        r = requests.get(
            endpoint.url_for_timeseries_tilejson(), params=params, timeout=60
        ).json()
        return r
    except Exception as e:
        print(f"Error fetching time series TileJSON from TiTiler CMR: {e}")
        return None

cog_bands(url, titiler_endpoint=None)

Get band names of a Cloud Optimized GeoTIFF (COG).

Parameters:

Name Type Description Default
url str

HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif

required
titiler_endpoint str

TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".

None

Returns:

Type Description
List

A list of band names.

Source code in leafmap/stac.py
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
def cog_bands(
    url: str,
    titiler_endpoint: Optional[str] = None,
) -> List:
    """Get band names of a Cloud Optimized GeoTIFF (COG).

    Args:
        url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
        titiler_endpoint (str, optional): TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".

    Returns:
        A list of band names.
    """

    if os.environ.get("USE_MKDOCS") is not None:
        return None

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
    try:
        r = requests.get(
            f"{titiler_endpoint}/cog/info",
            params={
                "url": url,
            },
        ).json()

        bands = [b[0] for b in r["band_descriptions"]]
        return bands
    except Exception as e:
        print(e)
        return []

cog_bounds(url, titiler_endpoint=None)

Get the bounding box of a Cloud Optimized GeoTIFF (COG).

Parameters:

Name Type Description Default
url str

HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif

required
titiler_endpoint str

TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".

None

Returns:

Name Type Description
list List

A list of values representing [left, bottom, right, top]

Source code in leafmap/stac.py
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
def cog_bounds(
    url: str,
    titiler_endpoint: Optional[str] = None,
) -> List:
    """Get the bounding box of a Cloud Optimized GeoTIFF (COG).

    Args:
        url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
        titiler_endpoint (str, optional): TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".

    Returns:
        list: A list of values representing [left, bottom, right, top]
    """
    if os.environ.get("USE_MKDOCS") is not None:
        return None

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
    try:
        r = requests.get(
            f"{titiler_endpoint}/cog/info.geojson", params={"url": url}
        ).json()
        return r["bbox"]
    except Exception as e:
        print(e)
        return None

cog_center(url, titiler_endpoint=None)

Get the centroid of a Cloud Optimized GeoTIFF (COG).

Parameters:

Name Type Description Default
url str

HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif

required
titiler_endpoint str

TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".

None

Returns:

Type Description
Tuple

A tuple representing (longitude, latitude).

Source code in leafmap/stac.py
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
def cog_center(
    url: str,
    titiler_endpoint: Optional[str] = None,
) -> Tuple:
    """Get the centroid of a Cloud Optimized GeoTIFF (COG).

    Args:
        url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
        titiler_endpoint (str, optional): TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".

    Returns:
        A tuple representing (longitude, latitude).
    """

    if os.environ.get("USE_MKDOCS") is not None:
        return None

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
    bounds = cog_bounds(url, titiler_endpoint)
    if bounds is None:
        return (None, None)
    else:
        center = (
            (bounds[0] + bounds[2]) / 2,
            (bounds[1] + bounds[3]) / 2,
        )  # (lat, lon)
        return center

cog_info(url, titiler_endpoint=None, return_geojson=False)

Get band statistics of a Cloud Optimized GeoTIFF (COG).

Parameters:

Name Type Description Default
url str

HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif

required
titiler_endpoint str

TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".

None

Returns:

Name Type Description
list List

A dictionary of band info.

Source code in leafmap/stac.py
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
def cog_info(
    url: str,
    titiler_endpoint: Optional[str] = None,
    return_geojson: Optional[bool] = False,
) -> List:
    """Get band statistics of a Cloud Optimized GeoTIFF (COG).

    Args:
        url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
        titiler_endpoint (str, optional): TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".

    Returns:
        list: A dictionary of band info.
    """
    if os.environ.get("USE_MKDOCS") is not None:
        return None

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
    info = "info"
    if return_geojson:
        info = "info.geojson"

    try:
        r = requests.get(
            f"{titiler_endpoint}/cog/{info}",
            params={
                "url": url,
            },
            timeout=10,
        ).json()
    except Exception as e:
        titiler_endpoint = "https://giswqs-titiler-endpoint.hf.space"
        r = requests.get(
            f"{titiler_endpoint}/cog/{info}",
            params={
                "url": url,
            },
            timeout=10,
        ).json()

    return r

cog_mosaic(links, titiler_endpoint=None, username='anonymous', layername=None, overwrite=False, verbose=True, **kwargs)

Creates a COG mosaic from a list of COG URLs.

Parameters:

Name Type Description Default
links list

A list containing COG HTTP URLs.

required
titiler_endpoint str

TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".

None
username str

User name for the titiler endpoint. Defaults to "anonymous".

'anonymous'
layername [type]

Layer name to use. Defaults to None.

None
overwrite bool

Whether to overwrite the layer name if existing. Defaults to False.

False
verbose bool

Whether to print out descriptive information. Defaults to True.

True

Raises:

Type Description
Exception

If the COG mosaic fails to create.

Returns:

Type Description
str

The tile URL for the COG mosaic.

Source code in leafmap/stac.py
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
def cog_mosaic(
    links: List,
    titiler_endpoint: Optional[str] = None,
    username: Optional[str] = "anonymous",
    layername=None,
    overwrite: Optional[bool] = False,
    verbose: Optional[bool] = True,
    **kwargs,
) -> str:
    """Creates a COG mosaic from a list of COG URLs.

    Args:
        links (list): A list containing COG HTTP URLs.
        titiler_endpoint (str, optional): TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".
        username (str, optional): User name for the titiler endpoint. Defaults to "anonymous".
        layername ([type], optional): Layer name to use. Defaults to None.
        overwrite (bool, optional): Whether to overwrite the layer name if existing. Defaults to False.
        verbose (bool, optional): Whether to print out descriptive information. Defaults to True.

    Raises:
        Exception: If the COG mosaic fails to create.

    Returns:
        The tile URL for the COG mosaic.
    """

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
    if layername is None:
        layername = "layer_X"

    try:
        if verbose:
            print("Creating COG masaic ...")

        # Create token
        r = requests.post(
            f"{titiler_endpoint}/tokens/create",
            json={"username": username, "scope": ["mosaic:read", "mosaic:create"]},
        ).json()
        token = r["token"]

        # Create mosaic
        requests.post(
            f"{titiler_endpoint}/mosaicjson/create",
            json={
                "username": username,
                "layername": layername,
                "files": links,
                # "overwrite": overwrite
            },
            params={
                "access_token": token,
            },
        ).json()

        r2 = requests.get(
            f"{titiler_endpoint}/mosaicjson/{username}.{layername}/tilejson.json",
        ).json()

        tiles = r2["tiles"][0]

        # Convert 127.0.0.1 to localhost for Google Colab browser access
        if "google.colab" in sys.modules and "127.0.0.1" in tiles:
            tiles = tiles.replace("http://127.0.0.1", "https://localhost")

        return tiles

    except Exception as e:
        raise Exception(e)

cog_mosaic_from_file(filepath, skip_rows=0, titiler_endpoint=None, username='anonymous', layername=None, overwrite=False, verbose=True, **kwargs)

Creates a COG mosaic from a csv/txt file stored locally for through HTTP URL.

Parameters:

Name Type Description Default
filepath str

Local path or HTTP URL to the csv/txt file containing COG URLs.

required
skip_rows int

The number of rows to skip in the file. Defaults to 0.

0
titiler_endpoint str

TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".

None
username str

User name for the titiler endpoint. Defaults to "anonymous".

'anonymous'
layername [type]

Layer name to use. Defaults to None.

None
overwrite bool

Whether to overwrite the layer name if existing. Defaults to False.

False
verbose bool

Whether to print out descriptive information. Defaults to True.

True

Returns:

Type Description
str

The tile URL for the COG mosaic.

Source code in leafmap/stac.py
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
def cog_mosaic_from_file(
    filepath: str,
    skip_rows: Optional[int] = 0,
    titiler_endpoint: Optional[str] = None,
    username: Optional[str] = "anonymous",
    layername=None,
    overwrite: Optional[bool] = False,
    verbose: Optional[bool] = True,
    **kwargs,
) -> str:
    """Creates a COG mosaic from a csv/txt file stored locally for through HTTP URL.

    Args:
        filepath (str): Local path or HTTP URL to the csv/txt file containing COG URLs.
        skip_rows (int, optional): The number of rows to skip in the file. Defaults to 0.
        titiler_endpoint (str, optional): TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".
        username (str, optional): User name for the titiler endpoint. Defaults to "anonymous".
        layername ([type], optional): Layer name to use. Defaults to None.
        overwrite (bool, optional): Whether to overwrite the layer name if existing. Defaults to False.
        verbose (bool, optional): Whether to print out descriptive information. Defaults to True.

    Returns:
        The tile URL for the COG mosaic.
    """
    import urllib

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
    links = []
    if filepath.startswith("http"):
        data = urllib.request.urlopen(filepath)
        for line in data:
            links.append(line.decode("utf-8").strip())

    else:
        with open(filepath) as f:
            links = [line.strip() for line in f.readlines()]

    links = links[skip_rows:]
    # print(links)
    mosaic = cog_mosaic(
        links, titiler_endpoint, username, layername, overwrite, verbose, **kwargs
    )
    return mosaic

cog_pixel_value(lon, lat, url, bidx, titiler_endpoint=None, verbose=True, **kwargs)

Get pixel value from COG.

Parameters:

Name Type Description Default
lon float

Longitude of the pixel.

required
lat float

Latitude of the pixel.

required
url str

HTTP URL to a COG, e.g., 'https://github.com/opengeos/data/releases/download/raster/Libya-2023-07-01.tif'

required
bidx str

Dataset band indexes (e.g bidx=1, bidx=1&bidx=2&bidx=3). Defaults to None.

required
titiler_endpoint str

TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

None
verbose bool

Print status messages. Defaults to True.

True

Returns:

Name Type Description
list List

A dictionary of band info.

Source code in leafmap/stac.py
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
def cog_pixel_value(
    lon: float,
    lat: float,
    url: str,
    bidx: Optional[str],
    titiler_endpoint: Optional[str] = None,
    verbose: Optional[bool] = True,
    **kwargs,
) -> List:
    """Get pixel value from COG.

    Args:
        lon (float): Longitude of the pixel.
        lat (float): Latitude of the pixel.
        url (str): HTTP URL to a COG, e.g., 'https://github.com/opengeos/data/releases/download/raster/Libya-2023-07-01.tif'
        bidx (str, optional): Dataset band indexes (e.g bidx=1, bidx=1&bidx=2&bidx=3). Defaults to None.
        titiler_endpoint (str, optional): TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.
        verbose (bool, optional): Print status messages. Defaults to True.

    Returns:
        list: A dictionary of band info.
    """
    if os.environ.get("USE_MKDOCS") is not None:
        return None

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
    kwargs["url"] = url
    if bidx is not None:
        kwargs["bidx"] = bidx

    r = requests.get(f"{titiler_endpoint}/cog/point/{lon},{lat}", params=kwargs).json()
    bands = cog_bands(url, titiler_endpoint)
    # if isinstance(titiler_endpoint, str):
    #     r = requests.get(f"{titiler_endpoint}/cog/point/{lon},{lat}", params=kwargs).json()
    # else:
    #     r = requests.get(
    #         titiler_endpoint.url_for_stac_pixel_value(lon, lat), params=kwargs
    #     ).json()

    if "detail" in r:
        if verbose:
            print(r["detail"])
        return None
    else:
        values = r["values"]
        result = dict(zip(bands, values))
        return result

cog_stats(url, titiler_endpoint=None)

Get band statistics of a Cloud Optimized GeoTIFF (COG).

Parameters:

Name Type Description Default
url str

HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif

required
titiler_endpoint str

TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".

None

Returns:

Name Type Description
list List

A dictionary of band statistics.

Source code in leafmap/stac.py
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
def cog_stats(
    url: str,
    titiler_endpoint: Optional[str] = None,
) -> List:
    """Get band statistics of a Cloud Optimized GeoTIFF (COG).

    Args:
        url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
        titiler_endpoint (str, optional): TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".

    Returns:
        list: A dictionary of band statistics.
    """
    if os.environ.get("USE_MKDOCS") is not None:
        return None

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
    try:
        r = requests.get(
            f"{titiler_endpoint}/cog/statistics",
            params={
                "url": url,
            },
            timeout=10,
        ).json()
        return r
    except Exception as e:
        print(e)
        return None

cog_tile(url, bands=None, titiler_endpoint=None, **kwargs)

Get a tile layer from a Cloud Optimized GeoTIFF (COG). Source code adapted from https://developmentseed.org/titiler/examples/notebooks/Working_with_CloudOptimizedGeoTIFF_simple/

Parameters:

Name Type Description Default
url str

HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif. Default to None

required
bands list

List of bands to use. Defaults to None.

None
titiler_endpoint str

TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".

None
**kwargs Any

Additional arguments to pass to the titiler endpoint. For more information about the available arguments, see https://developmentseed.org/titiler/endpoints/cog/#tiles. For example, to apply a rescaling to multiple bands, use something like rescale=["164,223","130,211","99,212"].

{}

Returns:

Type Description
Tuple

The COG tile layer URL and bounds.

Source code in leafmap/stac.py
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
def cog_tile(
    url,
    bands: Optional[str] = None,
    titiler_endpoint: Optional[str] = None,
    **kwargs,
) -> Tuple:
    """Get a tile layer from a Cloud Optimized GeoTIFF (COG).
        Source code adapted from https://developmentseed.org/titiler/examples/notebooks/Working_with_CloudOptimizedGeoTIFF_simple/

    Args:
        url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif. Default to None
        bands (list, optional): List of bands to use. Defaults to None.
        titiler_endpoint (str, optional): TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".
        **kwargs (Any): Additional arguments to pass to the titiler endpoint. For more information about the available arguments, see https://developmentseed.org/titiler/endpoints/cog/#tiles.
            For example, to apply a rescaling to multiple bands, use something like `rescale=["164,223","130,211","99,212"]`.

    Returns:
        The COG tile layer URL and bounds.
    """
    if os.environ.get("USE_MKDOCS") is not None:
        return None

    import json

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)

    kwargs["url"] = url

    try:
        band_names = cog_bands(url, titiler_endpoint)
    except Exception as e:
        titiler_endpoint = "https://giswqs-titiler-endpoint.hf.space"
        band_names = cog_bands(url, titiler_endpoint)

    if isinstance(bands, str):
        bands = [bands]

    if bands is None and "bidx" not in kwargs:
        if len(band_names) >= 3:
            kwargs["bidx"] = [1, 2, 3]
    elif isinstance(bands, list) and "bidx" not in kwargs:
        if all(isinstance(x, int) for x in bands):
            if len(set(bands)) == 1:
                bands = bands[0]
            kwargs["bidx"] = bands
        elif all(isinstance(x, str) for x in bands):
            if len(set(bands)) == 1:
                bands = bands[0]
            kwargs["bidx"] = [band_names.index(x) + 1 for x in bands]
        else:
            raise ValueError("Bands must be a list of integers or strings.")

    if "palette" in kwargs:
        kwargs["colormap_name"] = kwargs["palette"].lower()
        del kwargs["palette"]

    if "bidx" not in kwargs:
        kwargs["bidx"] = [1]
    elif isinstance(kwargs["bidx"], int):
        kwargs["bidx"] = [kwargs["bidx"]]

    if len(kwargs["bidx"]) == 1 and ("colormap" not in kwargs):
        colormap = _get_image_colormap(url)
        if colormap is not None:
            kwargs["colormap"] = colormap

    if "rescale" not in kwargs and ("colormap" not in kwargs):
        try:
            stats = cog_stats(url, titiler_endpoint)
        except Exception as e:
            titiler_endpoint = "https://giswqs-titiler-endpoint.hf.space"
            stats = cog_stats(url, titiler_endpoint)

        if stats is not None and "message" not in stats:
            try:
                rescale = []
                for i in band_names:
                    rescale.append(
                        "{},{}".format(
                            stats[i]["percentile_2"],
                            stats[i]["percentile_98"],
                        )
                    )
                kwargs["rescale"] = rescale
            except Exception as e:
                pass

    if "colormap" in kwargs and isinstance(kwargs["colormap"], dict):
        kwargs["colormap"] = json.dumps(kwargs["colormap"])

    TileMatrixSetId = "WebMercatorQuad"
    if "TileMatrixSetId" in kwargs.keys():
        TileMatrixSetId = kwargs["TileMatrixSetId"]
        kwargs.pop("TileMatrixSetId")

    if "default_vis" in kwargs.keys() and kwargs["default_vis"]:
        kwargs = {"url": url}

    try:
        r = requests.get(
            f"{titiler_endpoint}/cog/{TileMatrixSetId}/tilejson.json",
            params=kwargs,
            timeout=10,
        ).json()
    except Exception as e:
        print(e)
        return None
    tiles = r["tiles"][0]
    if titiler_endpoint.startswith("https://") and tiles.startswith("http://"):
        tiles = tiles.replace("http://", "https://")

    # Convert 127.0.0.1 to localhost for Google Colab browser access
    if "google.colab" in sys.modules and "127.0.0.1" in tiles:
        tiles = tiles.replace("http://127.0.0.1", "https://localhost")

    return tiles

cog_tile_vmin_vmax(url, bands=None, titiler_endpoint=None, percentile=True, **kwargs)

Get a tile layer from a Cloud Optimized GeoTIFF (COG) and return the minimum and maximum values.

Parameters:

Name Type Description Default
url str

HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif

required
bands list

List of bands to use. Defaults to None.

None
titiler_endpoint str

TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".

None
percentile bool

Whether to use percentiles or not. Defaults to True.

True
Source code in leafmap/stac.py
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
def cog_tile_vmin_vmax(
    url: str,
    bands: Optional[List] = None,
    titiler_endpoint: Optional[str] = None,
    percentile: Optional[bool] = True,
    **kwargs,
) -> Tuple:
    """Get a tile layer from a Cloud Optimized GeoTIFF (COG) and return the minimum and maximum values.

    Args:
        url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
        bands (list, optional): List of bands to use. Defaults to None.
        titiler_endpoint (str, optional): TiTiler endpoint. Defaults to "https://giswqs-titiler-endpoint.hf.space".
        percentile (bool, optional): Whether to use percentiles or not. Defaults to True.
    Returns:
        tuple: Returns the minimum and maximum values.
    """
    if os.environ.get("USE_MKDOCS") is not None:
        return None

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
    stats = cog_stats(url, titiler_endpoint)

    if isinstance(bands, str):
        bands = [bands]

    if bands is not None:
        stats = {s: stats[s] for s in stats if s in bands}

    if percentile:
        vmin = min([stats[s]["percentile_2"] for s in stats])
        vmax = max([stats[s]["percentile_98"] for s in stats])
    else:
        vmin = min([stats[s]["min"] for s in stats])
        vmax = max([stats[s]["max"] for s in stats])

    return vmin, vmax

create_mosaicjson(images, output)

Create a mosaicJSON file from a list of images.

Parameters:

Name Type Description Default
images str | list

A list of image URLs or a URL to a text file containing a list of image URLs.

required
output str

The output mosaicJSON file path.

required
Source code in leafmap/stac.py
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
def create_mosaicjson(images, output):
    """Create a mosaicJSON file from a list of images.

    Args:
        images (str | list): A list of image URLs or a URL to a text file containing a list of image URLs.
        output (str): The output mosaicJSON file path.

    """
    try:
        from cogeo_mosaic.backends import MosaicBackend
        from cogeo_mosaic.mosaic import MosaicJSON
    except ImportError:
        raise ImportError(
            "cogeo-mosaic is required to use this function. "
            "Install with `pip install cogeo-mosaic`."
        )

    if isinstance(images, str):
        if images.startswith("http"):
            import urllib.request

            with urllib.request.urlopen(images) as f:
                file_contents = f.read().decode("utf-8")
                images = file_contents.strip().split("\n")
        elif not os.path.exists(images):
            raise FileNotFoundError(f"{images} does not exist.")

    elif not isinstance(images, list):
        raise ValueError("images must be a list or a URL.")

    mosaic = MosaicJSON.from_urls(images)
    with MosaicBackend(output, mosaic_def=mosaic) as f:
        f.write(overwrite=True)

download_data_catalogs(out_dir=None, quiet=True, overwrite=False)

Download geospatial data catalogs from https://github.com/giswqs/geospatial-data-catalogs.

Parameters:

Name Type Description Default
out_dir str

The output directory. Defaults to None.

None
quiet bool

Whether to suppress the download progress bar. Defaults to True.

True
overwrite bool

Whether to overwrite the existing data catalog. Defaults to False.

False

Returns:

Name Type Description
str str

The path to the downloaded data catalog.

Source code in leafmap/stac.py
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
def download_data_catalogs(
    out_dir: Optional[str] = None,
    quiet: Optional[bool] = True,
    overwrite: Optional[bool] = False,
) -> str:
    """Download geospatial data catalogs from https://github.com/giswqs/geospatial-data-catalogs.

    Args:
        out_dir (str, optional): The output directory. Defaults to None.
        quiet (bool, optional): Whether to suppress the download progress bar. Defaults to True.
        overwrite (bool, optional): Whether to overwrite the existing data catalog. Defaults to False.

    Returns:
        str: The path to the downloaded data catalog.
    """
    import tempfile
    import zipfile

    import gdown

    if out_dir is None:
        out_dir = tempfile.gettempdir()
    elif not os.path.exists(out_dir):
        os.makedirs(out_dir)

    url = "https://github.com/giswqs/geospatial-data-catalogs/archive/refs/heads/master.zip"

    out_file = os.path.join(out_dir, "geospatial-data-catalogs.zip")
    work_dir = os.path.join(out_dir, "geospatial-data-catalogs-master")

    if os.path.exists(work_dir) and not overwrite:
        return work_dir
    else:
        gdown.download(url, out_file, quiet=quiet)
        with zipfile.ZipFile(out_file, "r") as zip_ref:
            zip_ref.extractall(out_dir)
        return work_dir

flatten_dict(my_dict, parent_key=False, sep='.')

Flattens a nested dictionary.

Parameters:

Name Type Description Default
my_dict dict

The dictionary to flatten.

required
parent_key bool

Whether to include the parent key. Defaults to False.

False
sep str

The separator to use. Defaults to '.'.

'.'

Returns:

Type Description
Dict[str, Any]

The flattened dictionary.

Source code in leafmap/stac.py
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
def flatten_dict(
    my_dict: Dict[str, Any], parent_key: bool = False, sep: str = "."
) -> Dict[str, Any]:
    """Flattens a nested dictionary.

    Args:
        my_dict (dict): The dictionary to flatten.
        parent_key (bool, optional): Whether to include the parent key. Defaults to False.
        sep (str, optional): The separator to use. Defaults to '.'.

    Returns:
        The flattened dictionary.
    """

    flat_dict = {}
    for key, value in my_dict.items():
        if not isinstance(value, dict):
            flat_dict[key] = value
        else:
            sub_dict = flatten_dict(value)
            for sub_key, sub_value in sub_dict.items():
                if parent_key:
                    flat_dict[parent_key + sep + sub_key] = sub_value
                else:
                    flat_dict[sub_key] = sub_value

    return flat_dict

Retrieve the URL of the GeoTIFF asset from a STAC Item.

Parameters:

Name Type Description Default
item_url str

The URL to a STAC Item JSON.

required

Returns:

Type Description
str

URL of the first .tif asset, or None if not found.

Source code in leafmap/stac.py
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
def get_cog_link_from_stac_item(item_url: str) -> str:
    """
    Retrieve the URL of the GeoTIFF asset from a STAC Item.

    Args:
        item_url (str): The URL to a STAC Item JSON.

    Returns:
        URL of the first .tif asset, or None if not found.
    """
    try:
        response = requests.get(item_url)
        response.raise_for_status()
        item = response.json()

        # Look for any asset ending in .tif
        for asset_key, asset in item.get("assets", {}).items():
            href = asset.get("href", "")
            if href.endswith(".tif") or ".tif?" in href:
                return href

        print("No .tif asset found in item.")
        return None
    except Exception as e:
        print(f"Failed to retrieve STAC item: {e}")
        return None

maxar_all_items(collection_id, return_gdf=True, assets=['visual'], verbose=True, **kwargs)

Retrieve STAC items from Maxar's public STAC API.

Parameters:

Name Type Description Default
collection_id str

The collection ID, e.g., Kahramanmaras-turkey-earthquake-23 Use maxar_collections() to retrieve all available collection IDs.

required
return_gdf bool

If True, return a GeoDataFrame. Defaults to True.

True
assets list

A list of asset names to include in the GeoDataFrame. It can be "visual", "ms_analytic", "pan_analytic", "data-mask". Defaults to ['visual'].

['visual']
verbose bool

If True, print progress. Defaults to True.

True
**kwargs Any

Additional keyword arguments to pass to the pystac Catalog.from_file() method.

{}

Returns:

Type Description
Union[GeoDataFrame, List[Dict[str, Any]]]

If return_gdf is True, return a GeoDataFrame.

Source code in leafmap/stac.py
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
def maxar_all_items(
    collection_id: str,
    return_gdf: Optional[bool] = True,
    assets: Optional[List] = ["visual"],
    verbose: Optional[bool] = True,
    **kwargs: Any,
) -> Union["gpd.GeoDataFrame", List[Dict[str, Any]]]:
    """Retrieve STAC items from Maxar's public STAC API.

    Args:
        collection_id (str): The collection ID, e.g., Kahramanmaras-turkey-earthquake-23
            Use maxar_collections() to retrieve all available collection IDs.
        return_gdf (bool, optional): If True, return a GeoDataFrame. Defaults to True.
        assets (list, optional): A list of asset names to include in the GeoDataFrame.
            It can be "visual", "ms_analytic", "pan_analytic", "data-mask". Defaults to ['visual'].
        verbose (bool, optional): If True, print progress. Defaults to True.
        **kwargs (Any): Additional keyword arguments to pass to the pystac Catalog.from_file() method.

    Returns:
        If return_gdf is True, return a GeoDataFrame.
    """

    child_ids = maxar_child_collections(collection_id, **kwargs)
    for index, child_id in enumerate(child_ids):
        if verbose:
            print(
                f"Processing ({str(index + 1).zfill(len(str(len(child_ids))))} out of {len(child_ids)}): {child_id} ..."
            )
        items = maxar_items(collection_id, child_id, return_gdf, assets, **kwargs)
        if return_gdf:
            if child_id == child_ids[0]:
                gdf = items
            else:
                gdf = pd.concat([gdf, items], ignore_index=True)
        else:
            if child_id == child_ids[0]:
                items_all = items
            else:
                items_all.extend(items)

    if return_gdf:
        return gdf
    else:
        return items_all

maxar_child_collections(collection_id, return_ids=True, **kwargs)

Get a list of Maxar child collections.

Parameters:

Name Type Description Default
collection_id str

The collection ID, e.g., Kahramanmaras-turkey-earthquake-23 Use maxar_collections() to retrieve all available collection IDs.

required
return_ids bool

Whether to return the collection ids. Defaults to True.

True
**kwargs Any

Additional keyword arguments to pass to the pystac Catalog.from_file() method.

{}

Returns:

Name Type Description
list List

A list of Maxar child collections.

Source code in leafmap/stac.py
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
def maxar_child_collections(
    collection_id: str, return_ids: Optional[bool] = True, **kwargs
) -> List:
    """Get a list of Maxar child collections.

    Args:
        collection_id (str): The collection ID, e.g., Kahramanmaras-turkey-earthquake-23
            Use maxar_collections() to retrieve all available collection IDs.
        return_ids (bool, optional): Whether to return the collection ids. Defaults to True.
        **kwargs (Any): Additional keyword arguments to pass to the pystac Catalog.from_file() method.

    Returns:
        list: A list of Maxar child collections.
    """

    import tempfile

    from pystac import Catalog

    file_path = os.path.join(tempfile.gettempdir(), f"maxar-{collection_id}.txt")
    if return_ids:
        if os.path.exists(file_path):
            with open(file_path, "r") as f:
                return [line.strip() for line in f.readlines()]

    if "MAXAR_STAC_API" in os.environ:
        url = os.environ["MAXAR_STAC_API"]
    else:
        url = "https://maxar-opendata.s3.amazonaws.com/events/catalog.json"

    root_catalog = Catalog.from_file(url, **kwargs)

    collections = root_catalog.get_child(collection_id).get_collections()

    if return_ids:
        collection_ids = [collection.id for collection in collections]
        with open(file_path, "w") as f:
            f.write("\n".join(collection_ids))
        return collection_ids

    else:
        return collections

maxar_collection_url(collection, dtype='geojson', raw=True)

Retrieve the URL to a Maxar Open Data collection.

Parameters:

Name Type Description Default
collection str

The collection ID, e.g., Kahramanmaras-turkey-earthquake-23. Use maxar_collections() to retrieve all available collection IDs.

required
dtype str

The data type. It can be 'geojson' or 'tsv'. Defaults to 'geojson'.

'geojson'
raw bool

If True, return the raw URL. Defaults to True.

True

Returns:

Type Description
str

The URL to the collection.

Source code in leafmap/stac.py
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
def maxar_collection_url(collection, dtype="geojson", raw=True) -> str:
    """Retrieve the URL to a Maxar Open Data collection.

    Args:
        collection (str): The collection ID, e.g., Kahramanmaras-turkey-earthquake-23.
            Use maxar_collections() to retrieve all available collection IDs.
        dtype (str, optional): The data type. It can be 'geojson' or 'tsv'. Defaults to 'geojson'.
        raw (bool, optional): If True, return the raw URL. Defaults to True.

    Returns:
        The URL to the collection.
    """
    collections = maxar_collections()
    if collection not in collections:
        raise ValueError(
            f"Invalid collection name. Use maxar_collections() to retrieve all available collection IDs."
        )

    if dtype not in ["geojson", "tsv"]:
        raise ValueError(f"Invalid dtype. It can be 'geojson' or 'tsv'.")

    if raw:
        url = f"https://raw.githubusercontent.com/giswqs/maxar-open-data/master/datasets/{collection}.{dtype}"
    else:
        url = f"https://github.com/giswqs/maxar-open-data/blob/master/datasets/{collection}.{dtype}"
    return url

maxar_collections(return_ids=True, **kwargs)

Get a list of Maxar collections.

Parameters:

Name Type Description Default
return_ids bool

Whether to return the collection ids. Defaults to True.

True
**kwargs Any

Additional keyword arguments to pass to the pystac Catalog.from_file() method.

{}

Returns:

Name Type Description
list List

A list of Maxar collections.

Source code in leafmap/stac.py
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
def maxar_collections(return_ids: Optional[bool] = True, **kwargs) -> List:
    """Get a list of Maxar collections.

    Args:
        return_ids (bool, optional): Whether to return the collection ids. Defaults to True.
        **kwargs (Any): Additional keyword arguments to pass to the pystac Catalog.from_file() method.

    Returns:
        list : A list of Maxar collections.
    """

    import tempfile

    import pandas as pd
    from pystac import Catalog

    if return_ids:
        url = "https://raw.githubusercontent.com/giswqs/maxar-open-data/master/datasets.csv"
        df = pd.read_csv(url)
        return df["dataset"].tolist()

    file_path = os.path.join(tempfile.gettempdir(), "maxar-collections.txt")
    if return_ids:
        if os.path.exists(file_path):
            with open(file_path, "r") as f:
                return [line.strip() for line in f.readlines()]

    if "MAXAR_STAC_API" in os.environ:
        url = os.environ["MAXAR_STAC_API"]
    else:
        url = "https://maxar-opendata.s3.amazonaws.com/events/catalog.json"

    root_catalog = Catalog.from_file(url, **kwargs)

    collections = root_catalog.get_collections()

    # if return_ids:
    #     collection_ids = [collection.id for collection in collections]
    #     with open(file_path, "w") as f:
    #         f.write("\n".join(collection_ids))

    #     return collection_ids
    # else:
    return collections

maxar_download(images, out_dir=None, quiet=False, proxy=None, speed=None, use_cookies=True, verify=True, id=None, fuzzy=False, resume=False, overwrite=False)

Download Mxar Open Data images.

Parameters:

Name Type Description Default
images str | images

The list of image links or a file path to a geojson or tsv containing the Maxar download links.

required
out_dir str

The output directory. Defaults to None.

None
quiet bool

Suppress terminal output. Default is False.

False
proxy str

Proxy. Defaults to None.

None
speed float

Download byte size per second (e.g., 256KB/s = 256 * 1024). Defaults to None.

None
use_cookies bool

Flag to use cookies. Defaults to True.

True
verify bool | str

Either a bool, in which case it controls whether the server's TLS certificate is verified, or a string, in which case it must be a path to a CA bundle to use. Default is True.. Defaults to True.

True
id str

Google Drive's file ID. Defaults to None.

None
fuzzy bool

Fuzzy extraction of Google Drive's file Id. Defaults to False.

False
resume bool

Resume the download from existing tmp file if possible. Defaults to False.

False
overwrite bool

Overwrite the file if it already exists. Defaults to False.

False
Source code in leafmap/stac.py
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
def maxar_download(
    images,
    out_dir=None,
    quiet=False,
    proxy=None,
    speed=None,
    use_cookies=True,
    verify=True,
    id=None,
    fuzzy=False,
    resume=False,
    overwrite=False,
):
    """Download Mxar Open Data images.

    Args:
        images (str | images): The list of image links or a file path to a geojson or tsv containing the Maxar download links.
        out_dir (str, optional): The output directory. Defaults to None.
        quiet (bool, optional): Suppress terminal output. Default is False.
        proxy (str, optional): Proxy. Defaults to None.
        speed (float, optional): Download byte size per second (e.g., 256KB/s = 256 * 1024). Defaults to None.
        use_cookies (bool, optional): Flag to use cookies. Defaults to True.
        verify (bool | str, optional): Either a bool, in which case it controls whether the server's TLS certificate is verified, or a string,
            in which case it must be a path to a CA bundle to use. Default is True.. Defaults to True.
        id (str, optional): Google Drive's file ID. Defaults to None.
        fuzzy (bool, optional): Fuzzy extraction of Google Drive's file Id. Defaults to False.
        resume (bool, optional): Resume the download from existing tmp file if possible. Defaults to False.
        overwrite (bool, optional): Overwrite the file if it already exists. Defaults to False.

    """
    import gdown

    if out_dir is None:
        out_dir = os.getcwd()

    if isinstance(images, str):
        if images.endswith(".geojson"):
            import geopandas as gpd

            data = gpd.read_file(images)
            images = data["visual"].tolist()
        elif images.endswith(".tsv"):
            import pandas as pd

            data = pd.read_csv(images, sep="\t")
            images = data["visual"].tolist()
        else:
            raise ValueError(f"Invalid file type. It can be 'geojson' or 'tsv'.")

    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    for index, image in enumerate(images):
        items = image.split("/")
        file_name = items[7] + ".tif"
        dir_name = items[-1].split("-")[0]
        if not os.path.exists(os.path.join(out_dir, dir_name)):
            os.makedirs(os.path.join(out_dir, dir_name))
        out_file = os.path.join(out_dir, dir_name, file_name)
        if os.path.exists(out_file) and (not overwrite):
            print(f"{out_file} already exists. Skipping...")
            continue
        if not quiet:
            print(
                f"Downloading {str(index + 1).zfill(len(str(len(images))))} out of {len(images)}: {dir_name}/{file_name}"
            )

        gdown.download(
            image, out_file, quiet, proxy, speed, use_cookies, verify, id, fuzzy, resume
        )

maxar_items(collection_id, child_id, return_gdf=True, assets=['visual'], **kwargs)

Retrieve STAC items from Maxar's public STAC API.

Parameters:

Name Type Description Default
collection_id str

The collection ID, e.g., Kahramanmaras-turkey-earthquake-23 Use maxar_collections() to retrieve all available collection IDs.

required
child_id str

The child collection ID, e.g., 1050050044DE7E00 Use maxar_child_collections() to retrieve all available child collection IDs.

required
return_gdf bool

If True, return a GeoDataFrame. Defaults to True.

True
assets list

A list of asset names to include in the GeoDataFrame. It can be "visual", "ms_analytic", "pan_analytic", "data-mask". Defaults to ['visual'].

['visual']
**kwargs Any

Additional keyword arguments to pass to the pystac Catalog.from_file() method.

{}

Returns:

Type Description
Union[GeoDataFrame, List[Dict[str, Any]]]

If return_gdf is True, return a GeoDataFrame.

Source code in leafmap/stac.py
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
def maxar_items(
    collection_id: str,
    child_id: str,
    return_gdf: Optional[bool] = True,
    assets: Optional[List] = ["visual"],
    **kwargs: Any,
) -> Union["gpd.GeoDataFrame", List[Dict[str, Any]]]:
    """Retrieve STAC items from Maxar's public STAC API.

    Args:
        collection_id (str): The collection ID, e.g., Kahramanmaras-turkey-earthquake-23
            Use maxar_collections() to retrieve all available collection IDs.
        child_id (str): The child collection ID, e.g., 1050050044DE7E00
            Use maxar_child_collections() to retrieve all available child collection IDs.
        return_gdf (bool, optional): If True, return a GeoDataFrame. Defaults to True.
        assets (list, optional): A list of asset names to include in the GeoDataFrame.
            It can be "visual", "ms_analytic", "pan_analytic", "data-mask". Defaults to ['visual'].
        **kwargs (Any): Additional keyword arguments to pass to the pystac Catalog.from_file() method.

    Returns:
        If return_gdf is True, return a GeoDataFrame.
    """

    import pickle
    import tempfile

    from pystac import Catalog, ItemCollection

    file_path = os.path.join(
        tempfile.gettempdir(), f"maxar-{collection_id}-{child_id}.pkl"
    )

    if os.path.exists(file_path):
        with open(file_path, "rb") as f:
            items = pickle.load(f)
        if return_gdf:
            import geopandas as gpd

            gdf = gpd.GeoDataFrame.from_features(
                pystac.ItemCollection(items).to_dict(), crs="EPSG:4326"
            )
            # convert bbox column type from list to string
            gdf["proj:bbox"] = [",".join(map(str, l)) for l in gdf["proj:bbox"]]
            if assets is not None:
                if isinstance(assets, str):
                    assets = [assets]
                elif not isinstance(assets, list):
                    raise ValueError("assets must be a list or a string.")

                for asset in assets:
                    links = []
                    for item in items:
                        if asset in item.get_assets():
                            link = item.get_assets()[asset].get_absolute_href()
                            links.append(link)
                        else:
                            links.append("")

                    gdf[asset] = links

            return gdf
        else:
            return items

    if "MAXAR_STAC_API" in os.environ:
        url = os.environ["MAXAR_STAC_API"]
    else:
        url = "https://maxar-opendata.s3.amazonaws.com/events/catalog.json"

    root_catalog = Catalog.from_file(url, **kwargs)

    collection = root_catalog.get_child(collection_id)
    child = collection.get_child(child_id)

    items = ItemCollection(child.get_all_items())

    with open(file_path, "wb") as f:
        pickle.dump(items, f)

    if return_gdf:
        import geopandas as gpd

        gdf = gpd.GeoDataFrame.from_features(
            pystac.ItemCollection(items).to_dict(), crs="EPSG:4326"
        )
        # convert bbox column type from list to string
        gdf["proj:bbox"] = [",".join(map(str, l)) for l in gdf["proj:bbox"]]
        if assets is not None:
            if isinstance(assets, str):
                assets = [assets]
            elif not isinstance(assets, list):
                raise ValueError("assets must be a list or a string.")

            for asset in assets:
                links = []
                for item in items:
                    if asset in item.get_assets():
                        link = item.get_assets()[asset].get_absolute_href()
                        links.append(link)
                    else:
                        links.append("")

                gdf[asset] = links

        return gdf
    else:
        return items

maxar_refresh()

Refresh the cached Maxar STAC items.

Source code in leafmap/stac.py
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
def maxar_refresh():
    """Refresh the cached Maxar STAC items."""
    import tempfile

    temp_dir = tempfile.gettempdir()
    for f in os.listdir(temp_dir):
        if f.startswith("maxar-"):
            os.remove(os.path.join(temp_dir, f))

    print("Maxar STAC items cache has been refreshed.")

Search Maxar Open Data by collection ID, date range, and/or bounding box.

Parameters:

Name Type Description Default
collection str

The collection ID, e.g., Kahramanmaras-turkey-earthquake-23. Use maxar_collections() to retrieve all available collection IDs.

required
start_date str

The start date, e.g., 2023-01-01. Defaults to None.

None
end_date str

The end date, e.g., 2023-12-31. Defaults to None.

None
bbox list | GeoDataFrame

The bounding box to filter by. Can be a list of 4 coordinates or a file path or a GeoDataFrame.

None
within bool

Whether to filter by the bounding box or the bounding box's interior. Defaults to False.

False
align bool

If True, automatically aligns GeoSeries based on their indices. If False, the order of elements is preserved.

True

Returns:

Type Description
GeoDataFrame

A GeoDataFrame containing the search results.

Source code in leafmap/stac.py
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
def maxar_search(
    collection, start_date=None, end_date=None, bbox=None, within=False, align=True
) -> "gpd.GeoDataFrame":
    """Search Maxar Open Data by collection ID, date range, and/or bounding box.

    Args:
        collection (str): The collection ID, e.g., Kahramanmaras-turkey-earthquake-23.
            Use maxar_collections() to retrieve all available collection IDs.
        start_date (str, optional): The start date, e.g., 2023-01-01. Defaults to None.
        end_date (str, optional): The end date, e.g., 2023-12-31. Defaults to None.
        bbox (list | GeoDataFrame): The bounding box to filter by. Can be a list of 4 coordinates or a file path or a GeoDataFrame.
        within (bool, optional): Whether to filter by the bounding box or the bounding box's interior. Defaults to False.
        align (bool, optional): If True, automatically aligns GeoSeries based on their indices. If False, the order of elements is preserved.

    Returns:
        A GeoDataFrame containing the search results.
    """
    import datetime

    import geopandas as gpd
    import pandas as pd
    from shapely.geometry import Polygon

    collections = maxar_collections()
    if collection not in collections:
        raise ValueError(
            f"Invalid collection name. Use maxar_collections() to retrieve all available collection IDs."
        )

    url = f"https://raw.githubusercontent.com/giswqs/maxar-open-data/master/datasets/{collection}.geojson"
    data = gpd.read_file(url)

    if bbox is not None:
        bbox = gpd.GeoDataFrame(
            geometry=[Polygon.from_bounds(*bbox)],
            crs="epsg:4326",
        )
        if within:
            data = data[data.within(bbox.union_all(), align=align)]
        else:
            data = data[data.intersects(bbox.union_all(), align=align)]

    date_field = "datetime"
    new_field = f"{date_field}_temp"
    data[new_field] = pd.to_datetime(data[date_field])

    if end_date is None:
        end_date = datetime.datetime.now().strftime("%Y-%m-%d")

    if start_date is None:
        start_date = data[new_field].min()

    mask = (data[new_field] >= start_date) & (data[new_field] <= end_date)
    result = data.loc[mask]
    return result.drop(columns=[new_field], axis=1)

maxar_tile_url(collection, tile, dtype='geojson', raw=True)

Retrieve the URL to a Maxar Open Data tile.

Args:

1
2
3
4
5
collection (str): The collection ID, e.g., Kahramanmaras-turkey-earthquake-23.
    Use maxar_collections() to retrieve all available collection IDs.
tile (str): The tile ID, e.g., 10300500D9F8E600.
dtype (str, optional): The data type. It can be 'geojson', 'json' or 'tsv'. Defaults to 'geojson'.
raw (bool, optional): If True, return the raw URL. Defaults to True.

Returns:

Type Description
str

The URL to the tile.

Source code in leafmap/stac.py
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
def maxar_tile_url(collection, tile, dtype="geojson", raw=True) -> str:
    """Retrieve the URL to a Maxar Open Data tile.

    Args:

        collection (str): The collection ID, e.g., Kahramanmaras-turkey-earthquake-23.
            Use maxar_collections() to retrieve all available collection IDs.
        tile (str): The tile ID, e.g., 10300500D9F8E600.
        dtype (str, optional): The data type. It can be 'geojson', 'json' or 'tsv'. Defaults to 'geojson'.
        raw (bool, optional): If True, return the raw URL. Defaults to True.

    Returns:
        The URL to the tile.
    """

    collections = maxar_collections()
    if collection not in collections:
        raise ValueError(
            f"Invalid collection name. Use maxar_collections() to retrieve all available collection IDs."
        )

    if dtype not in ["geojson", "json", "tsv"]:
        raise ValueError(f"Invalid dtype. It can be 'geojson', 'json' or 'tsv'.")

    if raw:
        url = f"https://raw.githubusercontent.com/giswqs/maxar-open-data/master/datasets/{collection}/{tile}.{dtype}"
    else:
        url = f"https://github.com/giswqs/maxar-open-data/blob/master/datasets/{collection}/{tile}.{dtype}"

    return url

Search OpenAerialMap (https://openaerialmap.org) and return a GeoDataFrame or list of image metadata.

Parameters:

Name Type Description Default
bbox list | str

The bounding box [xmin, ymin, xmax, ymax] to search within. Defaults to None.

None
start_date str

The start date to search within, such as "2015-04-20T00:00:00.000Z". Defaults to None.

None
end_date str

The end date to search within, such as "2015-04-21T00:00:00.000Z". Defaults to None.

None
limit int

The maximum number of results to return. Defaults to 100.

100
return_gdf bool

If True, return a GeoDataFrame, otherwise return a list. Defaults to True.

True
**kwargs Any

Additional keyword arguments to pass to the API. See https://hotosm.github.io/oam-api/

{}

Returns:

Type Description
Union[GeoDataFrame, List[Dict[str, Any]]]

If return_gdf is True, return a GeoDataFrame. Otherwise, return a list.

Source code in leafmap/stac.py
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
def oam_search(
    bbox=None,
    start_date=None,
    end_date=None,
    limit: int = 100,
    return_gdf: bool = True,
    **kwargs: Any,
) -> Union["gpd.GeoDataFrame", List[Dict[str, Any]]]:
    """Search OpenAerialMap (https://openaerialmap.org) and return a GeoDataFrame or list of image metadata.

    Args:
        bbox (list | str, optional): The bounding box [xmin, ymin, xmax, ymax] to search within. Defaults to None.
        start_date (str, optional): The start date to search within, such as "2015-04-20T00:00:00.000Z". Defaults to None.
        end_date (str, optional): The end date to search within, such as "2015-04-21T00:00:00.000Z". Defaults to None.
        limit (int, optional): The maximum number of results to return. Defaults to 100.
        return_gdf (bool, optional): If True, return a GeoDataFrame, otherwise return a list. Defaults to True.
        **kwargs: Additional keyword arguments to pass to the API. See https://hotosm.github.io/oam-api/

    Returns:
        If return_gdf is True, return a GeoDataFrame. Otherwise, return a list.
    """

    import geopandas as gpd
    from shapely.geometry import Polygon

    url = "https://api.openaerialmap.org/meta"
    if bbox is not None:
        if isinstance(bbox, str):
            bbox = [float(x) for x in bbox.split(",")]
        if not isinstance(bbox, list):
            raise ValueError("bbox must be a list.")
        if len(bbox) != 4:
            raise ValueError("bbox must be a list of 4 numbers.")
        bbox = ",".join(map(str, bbox))
        kwargs["bbox"] = bbox

    if start_date is not None:
        kwargs["acquisition_from"] = start_date

    if end_date is not None:
        kwargs["acquisition_to"] = end_date

    if limit is not None:
        kwargs["limit"] = limit

    try:
        r = requests.get(url, params=kwargs).json()
        if "results" in r:
            results = []
            for result in r["results"]:
                if "geojson" in result:
                    del result["geojson"]
                if "projection" in result:
                    del result["projection"]
                if "footprint" in result:
                    del result["footprint"]
                result = flatten_dict(result)
                results.append(result)

            if not return_gdf:
                return results
            else:
                df = pd.DataFrame(results)

                polygons = [Polygon.from_bounds(*bbox) for bbox in df["bbox"]]
                gdf = gpd.GeoDataFrame(geometry=polygons, crs="epsg:4326")

                return pd.concat([gdf, df], axis=1)

        else:
            print("No results found.")
            return None

    except Exception as e:
        return None

run_titiler(show_logs=False, start_port=8000, max_port=8100, return_titiler_endpoint=False)

Run TiTiler as a background service on an available port.

This function automatically detects Google Colab and adjusts the endpoint URL to use localhost remapping (https://localhost:{port}) for compatibility.

Parameters:

Name Type Description Default
show_logs bool

If True, stream logs to the notebook output.

False
start_port int

First port to try.

8000
max_port int

Last port to try (exclusive).

8100
return_titiler_endpoint bool

If True, return the titiler endpoint. Defaults to False.

False

Returns:

Name Type Description
tuple

(endpoint, port, process)

Source code in leafmap/stac.py
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
def run_titiler(
    show_logs: bool = False,
    start_port: int = 8000,
    max_port: int = 8100,
    return_titiler_endpoint: bool = False,
):
    """Run TiTiler as a background service on an available port.

    This function automatically detects Google Colab and adjusts the endpoint URL
    to use localhost remapping (https://localhost:{port}) for compatibility.

    Args:
        show_logs (bool): If True, stream logs to the notebook output.
        start_port (int): First port to try.
        max_port (int): Last port to try (exclusive).
        return_titiler_endpoint (bool): If True, return the titiler endpoint. Defaults to False.

    Returns:
        tuple: (endpoint, port, process)
    """

    import subprocess
    import socket
    import atexit
    import signal
    import time
    import threading

    def find_free_port(start, end):
        for port in range(start, end):
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                try:
                    s.bind(("127.0.0.1", port))
                    return port
                except OSError:
                    continue
        raise RuntimeError(f"No free port found between {start} and {end}")

    port = find_free_port(start_port, max_port)

    cmd = [
        "uvicorn",
        "titiler.application.main:app",
        "--host",
        "127.0.0.1",
        "--port",
        str(port),
        "--log-level",
        "info",
    ]

    proc = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE if show_logs else subprocess.DEVNULL,
        stderr=subprocess.STDOUT,
    )

    # Optionally stream logs in a background thread
    if show_logs:

        def stream_logs():
            for line in iter(proc.stdout.readline, b""):
                print(line.decode().rstrip())

        threading.Thread(target=stream_logs, daemon=True).start()

    # Wait a bit for startup
    time.sleep(2)

    # Always use http://127.0.0.1 for the endpoint so Python requests work
    # In Google Colab, tile URLs will be converted to https://localhost for browser access
    endpoint = f"http://127.0.0.1:{port}"

    if "google.colab" in sys.modules:
        print(f"🚀 TiTiler is running at {endpoint} (Google Colab mode)")
    else:
        print(f"🚀 TiTiler is running at {endpoint}")

    # Register cleanup on kernel shutdown
    def stop_titiler():
        if proc.poll() is None:
            print("🛑 Stopping TiTiler...")
            proc.send_signal(signal.SIGINT)
            try:
                proc.wait(timeout=5)
            except subprocess.TimeoutExpired:
                proc.kill()

    atexit.register(stop_titiler)

    os.environ["TITILER_ENDPOINT"] = endpoint
    os.environ["TITILER_PORT"] = str(port)
    os.environ["TITILER_PROCESS"] = str(proc)

    if return_titiler_endpoint:
        return endpoint, port, proc

run_titiler_xarray(show_logs=False, start_port=8000, max_port=8100)

Start a local titiler-xarray server for Zarr/NetCDF visualization.

This function starts a local titiler-xarray server that enables dynamic tile serving from Zarr and NetCDF datasets. The server runs in the background and will be automatically stopped when the Python kernel is terminated.

Requirements
  • titiler.xarray package: pip install "titiler.xarray[full]"
  • uvicorn: pip install uvicorn

Parameters:

Name Type Description Default
show_logs bool

If True, stream server logs to notebook output. Defaults to False.

False
start_port int

First port to try. Defaults to 8000.

8000
max_port int

Last port to try (exclusive). Defaults to 8100.

8100

Returns:

Name Type Description
str str

The endpoint URL of the running titiler-xarray server.

Example

endpoint = leafmap.run_titiler_xarray() m = leafmap.Map() m.add_zarr(url, variable="temperature", titiler_endpoint=endpoint)

Source code in leafmap/stac.py
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
def run_titiler_xarray(
    show_logs: bool = False,
    start_port: int = 8000,
    max_port: int = 8100,
) -> str:
    """Start a local titiler-xarray server for Zarr/NetCDF visualization.

    This function starts a local titiler-xarray server that enables dynamic
    tile serving from Zarr and NetCDF datasets. The server runs in the background
    and will be automatically stopped when the Python kernel is terminated.

    Requirements:
        - titiler.xarray package: pip install "titiler.xarray[full]"
        - uvicorn: pip install uvicorn

    Args:
        show_logs (bool): If True, stream server logs to notebook output.
            Defaults to False.
        start_port (int): First port to try. Defaults to 8000.
        max_port (int): Last port to try (exclusive). Defaults to 8100.

    Returns:
        str: The endpoint URL of the running titiler-xarray server.

    Example:
        >>> endpoint = leafmap.run_titiler_xarray()
        >>> m = leafmap.Map()
        >>> m.add_zarr(url, variable="temperature", titiler_endpoint=endpoint)
    """
    import subprocess
    import socket
    import atexit
    import signal
    import time
    import threading

    def find_free_port(start, end):
        for port in range(start, end):
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                try:
                    s.bind(("127.0.0.1", port))
                    return port
                except OSError:
                    continue
        raise RuntimeError(f"No free port found between {start} and {end}")

    port = find_free_port(start_port, max_port)

    # Create a simple titiler-xarray app inline
    app_code = """
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from titiler.xarray.factory import TilerFactory
from titiler.xarray.extensions import VariablesExtension

app = FastAPI(
    title="TiTiler-XArray",
    description="TiTiler application for Zarr/NetCDF datasets",
)

# Add CORS middleware to allow requests from any origin
# This is necessary for Jupyter notebooks and VSCode webviews
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

md = TilerFactory(
    router_prefix="/md",
    extensions=[VariablesExtension()],
)
app.include_router(md.router, prefix="/md", tags=["Multi Dimensional"])

@app.get("/health")
def health():
    return {"status": "ok"}
"""

    # Write the app to a temporary file
    import tempfile

    with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
        f.write(app_code)
        app_file = f.name

    module_name = os.path.splitext(os.path.basename(app_file))[0]

    cmd = [
        sys.executable,
        "-m",
        "uvicorn",
        f"{module_name}:app",
        "--host",
        "127.0.0.1",
        "--port",
        str(port),
        "--log-level",
        "info",
    ]

    # Change to the temp directory so uvicorn can find the module
    cwd = os.path.dirname(app_file)

    proc = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE if show_logs else subprocess.DEVNULL,
        stderr=subprocess.STDOUT,
        cwd=cwd,
    )

    # Optionally stream logs in a background thread
    if show_logs:

        def stream_logs():
            for line in iter(proc.stdout.readline, b""):
                print(line.decode().rstrip())

        threading.Thread(target=stream_logs, daemon=True).start()

    # Wait a bit for startup
    time.sleep(3)

    # Check if the server is running
    endpoint = f"http://127.0.0.1:{port}"

    try:
        response = requests.get(f"{endpoint}/health", timeout=5)
        if response.status_code != 200:
            raise RuntimeError("Server health check failed")
    except Exception as e:
        proc.kill()
        raise RuntimeError(
            f"Failed to start titiler-xarray server: {e}\n"
            "Make sure titiler.xarray is installed: pip install 'titiler.xarray[full]'"
        )

    if "google.colab" in sys.modules:
        print(f"🚀 TiTiler-XArray is running at {endpoint} (Google Colab mode)")
    else:
        print(f"🚀 TiTiler-XArray is running at {endpoint}")

    # Register cleanup on kernel shutdown
    def stop_server():
        if proc.poll() is None:
            print("🛑 Stopping TiTiler-XArray...")
            proc.send_signal(signal.SIGINT)
            try:
                proc.wait(timeout=5)
            except subprocess.TimeoutExpired:
                proc.kill()
        # Clean up temp file
        try:
            os.unlink(app_file)
        except Exception as e:
            # Best-effort cleanup; ignore failures but log for debugging
            print(
                f"Warning: failed to remove temporary TiTiler-XArray app file {app_file}: {e}"
            )

    atexit.register(stop_server)

    os.environ["TITILER_XARRAY_ENDPOINT"] = endpoint

    return endpoint

stac_assets(url=None, collection=None, item=None, titiler_endpoint=None, **kwargs)

Get all assets of a STAC item.

Parameters:

Name Type Description Default
url str

HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json

None
collection str

The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.

None
item str

The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.

None
titiler_endpoint str

TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

None

Returns:

Name Type Description
list List

A list of assets.

Source code in leafmap/stac.py
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
def stac_assets(
    url: str = None,
    collection: str = None,
    item: str = None,
    titiler_endpoint: Optional[str] = None,
    **kwargs,
) -> List:
    """Get all assets of a STAC item.

    Args:
        url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
        collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
        item (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
        titiler_endpoint (str, optional): TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

    Returns:
        list: A list of assets.
    """

    if url is None and collection is None:
        raise ValueError("Either url or collection must be specified.")

    if collection is not None and titiler_endpoint is None:
        titiler_endpoint = "planetary-computer"

    if isinstance(url, pystac.Item):
        try:
            url = url.self_href
        except Exception as e:
            print(e)

    if url is not None:
        kwargs["url"] = url
    if collection is not None:
        kwargs["collection"] = collection
    if item is not None:
        kwargs["item"] = item

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
    if isinstance(titiler_endpoint, str):
        r = requests.get(f"{titiler_endpoint}/stac/assets", params=kwargs).json()
    else:
        r = requests.get(titiler_endpoint.url_for_stac_assets(), params=kwargs).json()

    return r

stac_bands(url=None, collection=None, item=None, titiler_endpoint=None, **kwargs)

Get band names of a single SpatialTemporal Asset Catalog (STAC) item.

Parameters:

Name Type Description Default
url str

HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json

None
collection str

The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.

None
item str

The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.

None
titiler_endpoint str

TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

None

Returns:

Name Type Description
list List

A list of band names

Source code in leafmap/stac.py
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
def stac_bands(
    url: str = None,
    collection: str = None,
    item: str = None,
    titiler_endpoint: Optional[str] = None,
    **kwargs,
) -> List:
    """Get band names of a single SpatialTemporal Asset Catalog (STAC) item.

    Args:
        url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
        collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
        item (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
        titiler_endpoint (str, optional): TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

    Returns:
        list: A list of band names
    """

    if url is None and collection is None:
        raise ValueError("Either url or collection must be specified.")

    if collection is not None and titiler_endpoint is None:
        titiler_endpoint = "planetary-computer"

    if isinstance(url, pystac.Item):
        try:
            url = url.self_href
        except Exception as e:
            print(e)

    if url is not None:
        kwargs["url"] = url
    if collection is not None:
        kwargs["collection"] = collection
    if item is not None:
        kwargs["item"] = item

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
    try:
        if isinstance(titiler_endpoint, str):
            r = requests.get(f"{titiler_endpoint}/stac/assets", params=kwargs).json()
        else:
            r = requests.get(
                titiler_endpoint.url_for_stac_assets(), params=kwargs
            ).json()

        return r
    except Exception as e:
        print(e)
        return []

stac_bounds(url=None, collection=None, item=None, titiler_endpoint=None, **kwargs)

Get the bounding box of a single SpatialTemporal Asset Catalog (STAC) item.

Parameters:

Name Type Description Default
url str

HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json

None
collection str

The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.

None
item str

The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.

None
titiler_endpoint str

TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

None

Returns:

Name Type Description
list List

A list of values representing [left, bottom, right, top]

Source code in leafmap/stac.py
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
def stac_bounds(
    url: str = None,
    collection: str = None,
    item: str = None,
    titiler_endpoint: Optional[str] = None,
    **kwargs,
) -> List:
    """Get the bounding box of a single SpatialTemporal Asset Catalog (STAC) item.

    Args:
        url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
        collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
        item (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
        titiler_endpoint (str, optional): TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

    Returns:
        list: A list of values representing [left, bottom, right, top]
    """

    if url is None and collection is None:
        raise ValueError("Either url or collection must be specified.")

    if collection is not None and titiler_endpoint is None:
        titiler_endpoint = "planetary-computer"

    if isinstance(url, pystac.Item):
        try:
            url = url.self_href
        except Exception as e:
            print(e)

    if url is not None:
        kwargs["url"] = url
        response = requests.get(url)
        r = response.json()
        if "mosaicjson" in r:
            if "bounds" in r:
                return r["bounds"]

    if collection is not None:
        kwargs["collection"] = collection
    if item is not None:
        kwargs["item"] = item

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)

    try:
        if isinstance(titiler_endpoint, str):
            r = requests.get(
                f"{titiler_endpoint}/stac/info.geojson", params=kwargs
            ).json()
        else:
            r = requests.get(
                titiler_endpoint.url_for_stac_bounds(), params=kwargs
            ).json()

        # Try to get bounds from different response formats
        if "bbox" in r:
            bounds = r["bbox"]
        elif "properties" in r and isinstance(r["properties"], dict):
            # Handle GeoJSON Feature format (Planetary Computer)
            # Try to get bounds from properties.{asset}.bounds
            for key, value in r["properties"].items():
                if isinstance(value, dict) and "bounds" in value:
                    bounds = value["bounds"]
                    break
            else:
                # Fallback to geometry bbox if available
                if "geometry" in r and "coordinates" in r["geometry"]:
                    # Calculate bbox from geometry coordinates
                    coords = r["geometry"]["coordinates"][0]  # Assuming Polygon
                    lons = [c[0] for c in coords]
                    lats = [c[1] for c in coords]
                    bounds = [min(lons), min(lats), max(lons), max(lats)]
                else:
                    return None
        else:
            return None

        return bounds
    except Exception as e:
        print(e)
        return None

stac_center(url=None, collection=None, item=None, titiler_endpoint=None, **kwargs)

Get the centroid of a single SpatialTemporal Asset Catalog (STAC) item.

Parameters:

Name Type Description Default
url str

HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json

None
collection str

The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.

None
item str

The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.

None
titiler_endpoint str

TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

None

Returns:

Name Type Description
tuple Tuple[float, float]

A tuple representing (longitude, latitude)

Source code in leafmap/stac.py
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
def stac_center(
    url: str = None,
    collection: str = None,
    item: str = None,
    titiler_endpoint: Optional[str] = None,
    **kwargs,
) -> Tuple[float, float]:
    """Get the centroid of a single SpatialTemporal Asset Catalog (STAC) item.

    Args:
        url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
        collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
        item (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
        titiler_endpoint (str, optional): TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

    Returns:
        tuple: A tuple representing (longitude, latitude)
    """

    if isinstance(url, pystac.Item):
        try:
            url = url.self_href
        except Exception as e:
            print(e)

    bounds = stac_bounds(url, collection, item, titiler_endpoint, **kwargs)
    if bounds is None:
        return (None, None)
    else:
        center = (
            (bounds[0] + bounds[2]) / 2,
            (bounds[1] + bounds[3]) / 2,
        )  # (lon, lat)
        return center

stac_client(url, headers=None, parameters=None, ignore_conformance=False, modifier=None, request_modifier=None, stac_io=None, return_col_id=False, get_root=True, **kwargs)

Get the STAC client. It wraps the pystac.Client.open() method. See https://pystac-client.readthedocs.io/en/stable/api.html#pystac_client.Client.open

Parameters:

Name Type Description Default
url str

The URL of a STAC Catalog.

required
headers dict

A dictionary of additional headers to use in all requests made to any part of this Catalog/API. Defaults to None.

None
parameters dict

Optional dictionary of query string parameters to include in all requests. Defaults to None.

None
ignore_conformance bool

Ignore any advertised Conformance Classes in this Catalog/API. This means that functions will skip checking conformance, and may throw an unknown error if that feature is not supported, rather than a NotImplementedError. Defaults to False.

False
modifier function

A callable that modifies the children collection and items returned by this Client. This can be useful for injecting authentication parameters into child assets to access data from non-public sources. Defaults to None.

None
request_modifier function

A callable that either modifies a Request instance or returns a new one. This can be useful for injecting Authentication headers and/or signing fully-formed requests (e.g. signing requests using AWS SigV4). The callable should expect a single argument, which will be an instance of requests.Request. If the callable returns a requests.Request, that will be used. Alternately, the callable may simply modify the provided request object and return None.

None
stac_io stac_io

A StacApiIO object to use for I/O requests. Generally, leave this to the default. However in cases where customized I/O processing is required, a custom instance can be provided here.

None
return_col_id bool

Return the collection ID. Defaults to False.

False
get_root bool

Get the root link of the STAC object. Defaults to True.

True
**kwargs Any

Additional keyword arguments to pass to the pystac.Client.open() method.

{}

Returns:

Type Description
Any

The STAC client.

Source code in leafmap/stac.py
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
def stac_client(
    url: str,
    headers: Optional[Dict] = None,
    parameters: Optional[Dict] = None,
    ignore_conformance: Optional[bool] = False,
    modifier: Optional[Callable] = None,
    request_modifier: Optional[Callable] = None,
    stac_io=None,
    return_col_id: Optional[bool] = False,
    get_root: Optional[bool] = True,
    **kwargs: Any,
) -> Any:
    """Get the STAC client. It wraps the pystac.Client.open() method. See
        https://pystac-client.readthedocs.io/en/stable/api.html#pystac_client.Client.open

    Args:
        url (str): The URL of a STAC Catalog.
        headers (dict, optional):  A dictionary of additional headers to use in all requests
            made to any part of this Catalog/API. Defaults to None.
        parameters (dict, optional): Optional dictionary of query string parameters to include in all requests.
            Defaults to None.
        ignore_conformance (bool, optional): Ignore any advertised Conformance Classes in this Catalog/API.
            This means that functions will skip checking conformance, and may throw an unknown error
            if that feature is not supported, rather than a NotImplementedError. Defaults to False.
        modifier (function, optional): A callable that modifies the children collection and items
            returned by this Client. This can be useful for injecting authentication parameters
            into child assets to access data from non-public sources. Defaults to None.
        request_modifier (function, optional): A callable that either modifies a Request instance or returns
            a new one. This can be useful for injecting Authentication headers and/or signing fully-formed
            requests (e.g. signing requests using AWS SigV4). The callable should expect a single argument,
            which will be an instance of requests.Request. If the callable returns a requests.Request, that
            will be used. Alternately, the callable may simply modify the provided request object and
            return None.
        stac_io (pystac.stac_io, optional): A StacApiIO object to use for I/O requests. Generally, leave
            this to the default. However in cases where customized I/O processing is required, a custom
            instance can be provided here.
        return_col_id (bool, optional): Return the collection ID. Defaults to False.
        get_root (bool, optional): Get the root link of the STAC object. Defaults to True.
        **kwargs (Any): Additional keyword arguments to pass to the pystac.Client.open() method.

    Returns:
        The STAC client.
    """
    from pystac_client import Client

    collection_id = None

    if not get_root:
        return_col_id = False

    try:
        if get_root:
            root = stac_root_link(url, return_col_id=return_col_id)
            # Handle case where root is None
            if root is None:
                if return_col_id:
                    root = (url, None)
                else:
                    root = url
        else:
            root = url

        if return_col_id:
            client = Client.open(
                root[0],
                headers,
                parameters,
                ignore_conformance,
                modifier,
                request_modifier,
                stac_io,
                **kwargs,
            )
            collection_id = root[1]
            return client, collection_id
        else:
            client = Client.open(
                root,
                headers,
                parameters,
                ignore_conformance,
                modifier,
                request_modifier,
                stac_io,
                **kwargs,
            )
            return client, client.id

    except Exception as e:
        print(e)
        return None

stac_collections(url, return_ids=False, get_root=True, **kwargs)

Get the collection IDs of a STAC catalog.

Parameters:

Name Type Description Default
url str

The STAC catalog URL.

required
return_ids bool

Return collection IDs. Defaults to False.

False
get_root bool

Get the root link of the STAC object. Defaults to True.

True
**kwargs Any

Additional keyword arguments to pass to the stac_client() method.

{}

Returns:

Type Description
List

A list of collection IDs.

Source code in leafmap/stac.py
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
def stac_collections(
    url: str, return_ids: Optional[bool] = False, get_root=True, **kwargs
) -> List:
    """Get the collection IDs of a STAC catalog.

    Args:
        url (str): The STAC catalog URL.
        return_ids (bool, optional): Return collection IDs. Defaults to False.
        get_root (bool, optional): Get the root link of the STAC object. Defaults to True.
        **kwargs (Any): Additional keyword arguments to pass to the stac_client() method.

    Returns:
        A list of collection IDs.
    """
    try:
        client, _ = stac_client(url, get_root=get_root, **kwargs)
        collections = client.get_all_collections()

        if return_ids:
            return [c.id for c in collections]
        else:
            return collections

    except Exception as e:
        print(e)
        return None

stac_info(url=None, collection=None, item=None, assets=None, titiler_endpoint=None, **kwargs)

Get band info of a STAC item.

Parameters:

Name Type Description Default
url str

HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json

None
collection str

The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.

None
item str

The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.

None
assets str | list

The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].

None
titiler_endpoint str

TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

None

Returns:

Name Type Description
list List

A dictionary of band info.

Source code in leafmap/stac.py
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
def stac_info(
    url: str = None,
    collection: str = None,
    item: str = None,
    assets: Union[str, List] = None,
    titiler_endpoint: Optional[str] = None,
    **kwargs,
) -> List:
    """Get band info of a STAC item.

    Args:
        url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
        collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
        item (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
        assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
        titiler_endpoint (str, optional): TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

    Returns:
        list: A dictionary of band info.
    """

    if url is None and collection is None:
        raise ValueError("Either url or collection must be specified.")

    if collection is not None and titiler_endpoint is None:
        titiler_endpoint = "planetary-computer"

    if isinstance(url, pystac.Item):
        try:
            url = url.self_href
        except Exception as e:
            print(e)

    if url is not None:
        kwargs["url"] = url
    if collection is not None:
        kwargs["collection"] = collection
    if item is not None:
        kwargs["item"] = item
    if assets is not None:
        kwargs["assets"] = assets

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
    if isinstance(titiler_endpoint, str):
        r = requests.get(f"{titiler_endpoint}/stac/info", params=kwargs).json()
    else:
        r = requests.get(titiler_endpoint.url_for_stac_info(), params=kwargs).json()

    return r

stac_info_geojson(url=None, collection=None, item=None, assets=None, titiler_endpoint=None, **kwargs)

Get band info of a STAC item.

Parameters:

Name Type Description Default
url str

HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json

None
collection str

The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.

None
item str

The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.

None
assets str | list

The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].

None
titiler_endpoint str

TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

None

Returns:

Name Type Description
list List

A dictionary of band info.

Source code in leafmap/stac.py
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
def stac_info_geojson(
    url: str = None,
    collection: str = None,
    item: str = None,
    assets: Union[str, List] = None,
    titiler_endpoint: Optional[str] = None,
    **kwargs,
) -> List:
    """Get band info of a STAC item.

    Args:
        url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
        collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
        item (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
        assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
        titiler_endpoint (str, optional): TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

    Returns:
        list: A dictionary of band info.
    """

    if url is None and collection is None:
        raise ValueError("Either url or collection must be specified.")

    if collection is not None and titiler_endpoint is None:
        titiler_endpoint = "planetary-computer"

    if isinstance(url, pystac.Item):
        try:
            url = url.self_href
        except Exception as e:
            print(e)

    if url is not None:
        kwargs["url"] = url
    if collection is not None:
        kwargs["collection"] = collection
    if item is not None:
        kwargs["item"] = item
    if assets is not None:
        kwargs["assets"] = assets

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
    if isinstance(titiler_endpoint, str):
        r = requests.get(f"{titiler_endpoint}/stac/info.geojson", params=kwargs).json()
    else:
        r = requests.get(
            titiler_endpoint.url_for_stac_info_geojson(), params=kwargs
        ).json()

    return r

stac_min_max(url=None, collection=None, item=None, assets=None, titiler_endpoint=None, **kwargs)

Get the min and max values of a STAC item.

Parameters:

Name Type Description Default
url str

HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json

None
collection str

The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.

None
item str

The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.

None
assets str | list

The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].

None
titiler_endpoint str

TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

None

Returns:

Name Type Description
list List

A dictionary of band statistics.

Source code in leafmap/stac.py
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
def stac_min_max(
    url: str = None,
    collection: str = None,
    item: str = None,
    assets: Union[str, List] = None,
    titiler_endpoint: Optional[str] = None,
    **kwargs,
) -> List:
    """Get the min and max values of a STAC item.

    Args:
        url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
        collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
        item (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
        assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
        titiler_endpoint (str, optional): TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

    Returns:
        list: A dictionary of band statistics.
    """

    stats = stac_stats(url, collection, item, assets, titiler_endpoint, **kwargs)

    values = stats.values()

    try:
        min_values = [v["min"] for v in values]
        max_values = [v["max"] for v in values]

        return min(min_values), max(max_values)
    except Exception as e:
        return None, None

stac_object_type(url, **kwargs)

Get the STAC object type.

Parameters:

Name Type Description Default
url str

The STAC object URL.

required
**kwargs Any

Keyword arguments for pystac.STACObject.from_file(). Defaults to None.

{}

Returns:

Type Description
str

The STAC object type, can be catalog, collection, or item.

Source code in leafmap/stac.py
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
def stac_object_type(url: str, **kwargs) -> str:
    """Get the STAC object type.

    Args:
        url (str): The STAC object URL.
        **kwargs (Any): Keyword arguments for pystac.STACObject.from_file(). Defaults to None.

    Returns:
        The STAC object type, can be catalog, collection, or item.
    """
    try:
        obj = pystac.STACObject.from_file(url, **kwargs)

        if isinstance(obj, pystac.Collection):
            return "collection"
        elif isinstance(obj, pystac.Item):
            return "item"
        elif isinstance(obj, pystac.Catalog):
            return "catalog"

    except Exception as e:
        print(e)
        return None

stac_pixel_value(lon, lat, url=None, collection=None, item=None, assets=None, titiler_endpoint=None, verbose=True, **kwargs)

Get pixel value from STAC assets.

Parameters:

Name Type Description Default
lon float

Longitude of the pixel.

required
lat float

Latitude of the pixel.

required
url str

HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json

None
collection str

The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.

None
item str

The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.

None
assets str | list

The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].

None
titiler_endpoint str

TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

None
verbose bool

Print out the error message. Defaults to True.

True

Returns:

Type Description
Dict[str, Any]

A dictionary of pixel values for each asset.

Source code in leafmap/stac.py
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
def stac_pixel_value(
    lon: float,
    lat: float,
    url: str = None,
    collection: str = None,
    item: str = None,
    assets: Union[str, List] = None,
    titiler_endpoint: Optional[str] = None,
    verbose: Optional[bool] = True,
    **kwargs: Any,
) -> Dict[str, Any]:
    """Get pixel value from STAC assets.

    Args:
        lon (float): Longitude of the pixel.
        lat (float): Latitude of the pixel.
        url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
        collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
        item (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
        assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
        titiler_endpoint (str, optional): TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.
        verbose (bool, optional): Print out the error message. Defaults to True.

    Returns:
        A dictionary of pixel values for each asset.
    """

    if url is None and collection is None:
        raise ValueError("Either url or collection must be specified.")

    if collection is not None and titiler_endpoint is None:
        titiler_endpoint = "planetary-computer"

    if isinstance(url, pystac.Item):
        try:
            url = url.self_href
        except Exception as e:
            print(e)

    if url is not None:
        kwargs["url"] = url
    if collection is not None:
        kwargs["collection"] = collection
    if item is not None:
        kwargs["item"] = item

    if assets is None:
        assets = stac_assets(
            url=url,
            collection=collection,
            item=item,
            titiler_endpoint=titiler_endpoint,
        )
    kwargs["assets"] = assets

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
    if isinstance(titiler_endpoint, str):
        r = requests.get(
            f"{titiler_endpoint}/stac/point/{lon},{lat}", params=kwargs
        ).json()
    else:
        r = requests.get(
            titiler_endpoint.url_for_stac_pixel_value(lon, lat), params=kwargs
        ).json()

    if "detail" in r:
        if verbose:
            print(r["detail"])
        return None
    else:
        values = r["values"]
        if isinstance(assets, str):
            assets = assets.split(",")
        result = dict(zip(assets, values))
        return result

Get the root link of a STAC object.

Parameters:

Name Type Description Default
url str

The STAC object URL.

required
return_col_id bool

Return the collection ID if the STAC object is a collection. Defaults to False.

False
**kwargs Any

Keyword arguments for pystac.STACObject.from_file().

{}

Returns:

Type Description
str

The root link of the STAC object. Returns None if no root link found.

str

If return_col_id is True, returns (root_link, collection_id).

Raises:

Type Description
ValueError

If FeatureCollection contains no features.

Source code in leafmap/stac.py
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
def stac_root_link(url: str, return_col_id: Optional[bool] = False, **kwargs) -> str:
    """Get the root link of a STAC object.

    Args:
        url (str): The STAC object URL.
        return_col_id (bool, optional): Return the collection ID if the STAC object
            is a collection. Defaults to False.
        **kwargs (Any): Keyword arguments for pystac.STACObject.from_file().

    Returns:
        The root link of the STAC object. Returns None if no root link found.
        If return_col_id is True, returns (root_link, collection_id).

    Raises:
        ValueError: If FeatureCollection contains no features.
    """
    collection_id = None
    try:
        response = requests.get(url, **kwargs)
        response.raise_for_status()
        data = response.json()

        # Handle FeatureCollection from /items endpoint
        if data.get("type") == "FeatureCollection":
            features = data.get("features", [])
            if not features:
                raise ValueError("FeatureCollection contains no features.")
            item = pystac.Item.from_dict(features[0])
            collection_id = item.collection_id
            root = item.get_root_link()
            return (
                (root.get_href() if root else item.get_self_href(), collection_id)
                if return_col_id
                else root.get_href() if root else item.get_self_href()
            )

        # Handle STAC API objects (Collection, Catalog, etc.)
        links = data.get("links", [])
        root_href = None
        self_href = None

        for link in links:
            if link.get("rel") == "root":
                root_href = link.get("href")
            elif link.get("rel") == "self":
                self_href = link.get("href")

        # Get collection/catalog ID if requested
        if return_col_id:
            if data.get("type") in ["Collection", "Catalog"]:
                collection_id = data.get("id")

        # Determine the root href:
        # 1. If there's an explicit root link, use it
        # 2. If there's no root link but there's a self link, the self link is the root
        #    (this is common for root catalogs in STAC APIs)
        # 3. Otherwise, fall back to parsing as a regular STAC object
        if root_href:
            return (root_href, collection_id) if return_col_id else root_href
        elif self_href and not root_href:
            # When there's no root link, self link often indicates this IS the root
            return (self_href, collection_id) if return_col_id else self_href

        # Fallback: parse as regular STAC object using pystac
        obj = pystac.STACObject.from_dict(data)
        if isinstance(obj, (pystac.Collection, pystac.Catalog)):
            collection_id = obj.id

        root = obj.get_root_link()
        href = root.get_href() if root else obj.get_self_href()
        return (href, collection_id) if return_col_id else href

    except Exception as e:
        print(f"Failed to resolve STAC root from {url}: {e}")
        return (None, None) if return_col_id else None

Search a STAC API. The function wraps the pysatc_client.Client.search() method. See https://pystac-client.readthedocs.io/en/stable/api.html#pystac_client.Client.search

Parameters:

Name Type Description Default
url str

The STAC API URL.

required
method str

The HTTP method to use when making a request to the service. This must be either "GET", "POST", or None. If None, this will default to "POST". If a "POST" request receives a 405 status for the response, it will automatically retry with "GET" for all subsequent requests. Defaults to "POST".

'POST'
max_items init

The maximum number of items to return from the search, even if there are more matching results. This client to limit the total number of Items returned from the items(), item_collections(), and items_as_dicts methods(). The client will continue to request pages of items until the number of max items is reached. This parameter defaults to 100. Setting this to None will allow iteration over a possibly very large number of results.. Defaults to None.

None
limit int

A recommendation to the service as to the number of items to return per page of results. Defaults to 100.

100
ids list

List of one or more Item ids to filter on. Defaults to None.

None
collections list

List of one or more Collection IDs or pystac.Collection instances. Only Items in one of the provided Collections will be searched. Defaults to None.

None
bbox list | tuple

A list, tuple, or iterator representing a bounding box of 2D or 3D coordinates. Results will be filtered to only those intersecting the bounding box. Defaults to None.

None
intersects str | dict

A string or dictionary representing a GeoJSON geometry, or an object that implements a geo_interface property, as supported by several libraries including Shapely, ArcPy, PySAL, and geojson. Results filtered to only those intersecting the geometry. Defaults to None.

None
datetime str

Either a single datetime or datetime range used to filter results. You may express a single datetime using a datetime.datetime instance, a RFC 3339-compliant timestamp, or a simple date string (see below). Instances of datetime.datetime may be either timezone aware or unaware. Timezone aware instances will be converted to a UTC timestamp before being passed to the endpoint. Timezone unaware instances are assumed to represent UTC timestamps. You may represent a datetime range using a "/" separated string as described in the spec, or a list, tuple, or iterator of 2 timestamps or datetime instances. For open-ended ranges, use either ".." ('2020-01-01:00:00:00Z/..', ['2020-01-01:00:00:00Z', '..']) or a value of None (['2020-01-01:00:00:00Z', None]). If using a simple date string, the datetime can be specified in YYYY-mm-dd format, optionally truncating to YYYY-mm or just YYYY. Simple date strings will be expanded to include the entire time period. Defaults to None.

None
query list

List or JSON of query parameters as per the STAC API query extension. such as {"eo:cloud_cover":{"lt":10}}. Defaults to None.

None
filter dict

JSON of query parameters as per the STAC API filter extension. Defaults to None.

None
filter_lang str

Language variant used in the filter body. If filter is a dictionary or not provided, defaults to ‘cql2-json’. If filter is a string, defaults to cql2-text. Defaults to None.

None
sortby str | list

A single field or list of fields to sort the response by. such as [{ 'field': 'properties.eo:cloud_cover', 'direction': 'asc' }]. Defaults to None.

None
fields list

A list of fields to include in the response. Note this may result in invalid STAC objects, as they may not have required fields. Use items_as_dicts to avoid object unmarshalling errors. Defaults to None.

None
get_collection bool

True to return a pystac.ItemCollection. Defaults to False.

False
get_items bool

True to return a list of pystac.Item. Defaults to False.

False
get_assets bool

True to return a list of pystac.Asset. Defaults to False.

False
get_links bool

True to return a list of links. Defaults to False.

False
get_gdf bool

True to return a GeoDataFrame. Defaults to False.

False
get_info bool

True to return a dictionary of STAC items. Defaults to False.

False
get_root bool

Get the root link of the STAC object. Defaults to True.

True
**kwargs Any

Additional keyword arguments to pass to the stac_client() function.

{}

Returns:

Type Description
List

The search results as a list of links or a pystac.ItemCollection.

Source code in leafmap/stac.py
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
def stac_search(
    url: str,
    method: Optional[str] = "POST",
    max_items: Optional[int] = None,
    limit: Optional[int] = 100,
    ids: Optional[List] = None,
    collections: Optional[List] = None,
    bbox: Optional[Union[List, Tuple]] = None,
    intersects: Optional[Union[str, Dict]] = None,
    datetime: Optional[str] = None,
    query: Optional[List] = None,
    filter: Optional[Dict] = None,
    filter_lang: Optional[str] = None,
    sortby: Optional[Union[List, str]] = None,
    fields: Optional[List] = None,
    get_collection: Optional[bool] = False,
    get_items: Optional[bool] = False,
    get_assets: Optional[bool] = False,
    get_links: Optional[bool] = False,
    get_gdf: Optional[bool] = False,
    get_info: Optional[bool] = False,
    get_root: Optional[bool] = True,
    **kwargs,
) -> List:
    """Search a STAC API. The function wraps the pysatc_client.Client.search() method. See
        https://pystac-client.readthedocs.io/en/stable/api.html#pystac_client.Client.search

    Args:
        url (str): The STAC API URL.
        method (str, optional): The HTTP method to use when making a request to the service.
            This must be either "GET", "POST", or None. If None, this will default to "POST".
            If a "POST" request receives a 405 status for the response, it will automatically
            retry with "GET" for all subsequent requests. Defaults to "POST".
        max_items (init, optional): The maximum number of items to return from the search,
            even if there are more matching results. This client to limit the total number of
            Items returned from the items(), item_collections(), and items_as_dicts methods().
            The client will continue to request pages of items until the number of max items
            is reached. This parameter defaults to 100. Setting this to None will allow iteration
            over a possibly very large number of results.. Defaults to None.
        limit (int, optional): A recommendation to the service as to the number of items to
            return per page of results. Defaults to 100.
        ids (list, optional): List of one or more Item ids to filter on. Defaults to None.
        collections (list, optional): List of one or more Collection IDs or pystac.Collection instances.
            Only Items in one of the provided Collections will be searched. Defaults to None.
        bbox (list | tuple, optional): A list, tuple, or iterator representing a bounding box of 2D
            or 3D coordinates. Results will be filtered to only those intersecting the bounding box.
            Defaults to None.
        intersects (str | dict, optional):  A string or dictionary representing a GeoJSON geometry, or
            an object that implements a __geo_interface__ property, as supported by several
            libraries including Shapely, ArcPy, PySAL, and geojson. Results filtered to only
            those intersecting the geometry. Defaults to None.
        datetime (str, optional): Either a single datetime or datetime range used to filter results.
            You may express a single datetime using a datetime.datetime instance, a RFC 3339-compliant
            timestamp, or a simple date string (see below). Instances of datetime.datetime may be either
            timezone aware or unaware. Timezone aware instances will be converted to a UTC timestamp
            before being passed to the endpoint. Timezone unaware instances are assumed to represent
            UTC timestamps. You may represent a datetime range using a "/" separated string as described
            in the spec, or a list, tuple, or iterator of 2 timestamps or datetime instances.
            For open-ended ranges, use either ".." ('2020-01-01:00:00:00Z/..', ['2020-01-01:00:00:00Z', '..'])
            or a value of None (['2020-01-01:00:00:00Z', None]). If using a simple date string,
            the datetime can be specified in YYYY-mm-dd format, optionally truncating to
            YYYY-mm or just YYYY. Simple date strings will be expanded to include the entire
            time period. Defaults to None.
        query (list, optional): List or JSON of query parameters as per the STAC API query extension.
            such as {"eo:cloud_cover":{"lt":10}}. Defaults to None.
        filter (dict, optional): JSON of query parameters as per the STAC API filter extension. Defaults to None.
        filter_lang (str, optional): Language variant used in the filter body. If filter is a dictionary
            or not provided, defaults to ‘cql2-json’. If filter is a string, defaults to cql2-text. Defaults to None.
        sortby (str | list, optional): A single field or list of fields to sort the response by.
            such as [{ 'field': 'properties.eo:cloud_cover', 'direction': 'asc' }]. Defaults to None.
        fields (list, optional): A list of fields to include in the response. Note this may result in
            invalid STAC objects, as they may not have required fields. Use items_as_dicts to avoid object
            unmarshalling errors. Defaults to None.
        get_collection (bool, optional): True to return a pystac.ItemCollection. Defaults to False.
        get_items (bool, optional): True to return a list of pystac.Item. Defaults to False.
        get_assets (bool, optional): True to return a list of pystac.Asset. Defaults to False.
        get_links (bool, optional): True to return a list of links. Defaults to False.
        get_gdf (bool, optional): True to return a GeoDataFrame. Defaults to False.
        get_info (bool, optional): True to return a dictionary of STAC items. Defaults to False.
        get_root (bool, optional): Get the root link of the STAC object. Defaults to True.
        **kwargs (Any): Additional keyword arguments to pass to the stac_client() function.

    Returns:
        The search results as a list of links or a pystac.ItemCollection.
    """

    client, collection_id = stac_client(
        url, return_col_id=True, get_root=get_root, **kwargs
    )

    if client is None:
        return None
    else:
        if isinstance(intersects, dict) and "geometry" in intersects:
            intersects = intersects["geometry"]

        if collection_id is not None and collections is None:
            collections = [collection_id]

        search = client.search(
            method=method,
            max_items=max_items,
            limit=limit,
            ids=ids,
            collections=collections,
            bbox=bbox,
            intersects=intersects,
            datetime=datetime,
            query=query,
            filter=filter,
            filter_lang=filter_lang,
            sortby=sortby,
            fields=fields,
        )

        if get_collection:
            return search.item_collection()
        elif get_items:
            return list(search.items())
        elif get_assets:
            assets = {}
            for item in search.items():
                assets[item.id] = {}
                for key, value in item.get_assets().items():
                    assets[item.id][key] = value.href
            return assets
        elif get_links:
            return [item.get_self_href() for item in search.items()]
        elif get_gdf:
            import geopandas as gpd

            gdf = gpd.GeoDataFrame.from_features(
                search.item_collection().to_dict(), crs="EPSG:4326"
            )
            return gdf
        elif get_info:
            items = search.items()
            info = {}
            for item in items:
                info[item.id] = {
                    "id": item.id,
                    "href": item.get_self_href(),
                    "bands": list(item.get_assets().keys()),
                    "assets": item.get_assets(),
                }
            return info
        else:
            return search

stac_search_to_df(search, **kwargs)

Convert STAC search result to a DataFrame.

Parameters:

Name Type Description Default
search item_search

The search result returned by leafmap.stac_search().

required
**kwargs Any

Additional keyword arguments to pass to the DataFrame.drop() function.

{}

Returns:

Type Description
DataFrame

A Pandas DataFrame object.

Source code in leafmap/stac.py
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
def stac_search_to_df(search, **kwargs) -> pd.DataFrame:
    """Convert STAC search result to a DataFrame.

    Args:
        search (pystac_client.item_search): The search result returned by leafmap.stac_search().
        **kwargs (Any): Additional keyword arguments to pass to the DataFrame.drop() function.

    Returns:
        A Pandas DataFrame object.
    """
    gdf = stac_search_to_gdf(search)
    return gdf.drop(columns=["geometry"], **kwargs)

stac_search_to_dict(search, **kwargs)

Convert STAC search result to a dictionary.

Parameters:

Name Type Description Default
search item_search

The search result returned by leafmap.stac_search().

required

Returns:

Name Type Description
dict Dict

A dictionary of STAC items, with the stac item id as the key, and the stac item as the value.

Source code in leafmap/stac.py
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
def stac_search_to_dict(search, **kwargs) -> Dict:
    """Convert STAC search result to a dictionary.

    Args:
        search (pystac_client.item_search): The search result returned by leafmap.stac_search().

    Returns:
        dict: A dictionary of STAC items, with the stac item id as the key, and the stac item as the value.
    """

    items = list(search.item_collection())
    info = {}
    for item in items:
        info[item.id] = {
            "id": item.id,
            "href": item.get_self_href(),
            "bands": list(item.get_assets().keys()),
            "assets": item.get_assets(),
        }
        links = {}
        assets = item.get_assets()
        for key, value in assets.items():
            links[key] = value.href
        info[item.id]["links"] = links
    return info

stac_search_to_gdf(search, **kwargs)

Convert STAC search result to a GeoDataFrame.

Parameters:

Name Type Description Default
search item_search

The search result returned by leafmap.stac_search().

required
**kwargs Any

Additional keyword arguments to pass to the GeoDataFrame.from_features() function.

{}

Returns:

Type Description
GeoDataFrame

A GeoPandas GeoDataFrame object.

Source code in leafmap/stac.py
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
def stac_search_to_gdf(search, **kwargs: Any) -> "gpd.GeoDataFrame":
    """Convert STAC search result to a GeoDataFrame.

    Args:
        search (pystac_client.item_search): The search result returned by leafmap.stac_search().
        **kwargs (Any): Additional keyword arguments to pass to the GeoDataFrame.from_features() function.

    Returns:
        A GeoPandas GeoDataFrame object.
    """
    import geopandas as gpd

    gdf = gpd.GeoDataFrame.from_features(
        search.item_collection().to_dict(), crs="EPSG:4326", **kwargs
    )
    return gdf

stac_search_to_list(search, **kwargs)

Convert STAC search result to a list.

Parameters:

Name Type Description Default
search item_search

The search result returned by leafmap.stac_search().

required

Returns:

Name Type Description
list List

A list of STAC items.

Source code in leafmap/stac.py
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
def stac_search_to_list(search, **kwargs) -> List:
    """Convert STAC search result to a list.

    Args:
        search (pystac_client.item_search): The search result returned by leafmap.stac_search().

    Returns:
        list: A list of STAC items.
    """

    return search.item_collections()

stac_stats(url=None, collection=None, item=None, assets=None, titiler_endpoint=None, **kwargs)

Get band statistics of a STAC item.

Parameters:

Name Type Description Default
url str

HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json

None
collection str

The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.

None
item str

The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.

None
assets str | list

The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].

None
titiler_endpoint str

TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

None

Returns:

Name Type Description
list List

A dictionary of band statistics.

Source code in leafmap/stac.py
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
def stac_stats(
    url: str = None,
    collection: str = None,
    item: str = None,
    assets: Union[str, List] = None,
    titiler_endpoint: Optional[str] = None,
    **kwargs,
) -> List:
    """Get band statistics of a STAC item.

    Args:
        url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
        collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
        item (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
        assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
        titiler_endpoint (str, optional): TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "planetary-computer", "pc". Defaults to None.

    Returns:
        list: A dictionary of band statistics.
    """

    if url is None and collection is None:
        raise ValueError("Either url or collection must be specified.")

    if collection is not None and titiler_endpoint is None:
        titiler_endpoint = "planetary-computer"

    if isinstance(url, pystac.Item):
        try:
            url = url.self_href
        except Exception as e:
            print(e)

    if url is not None:
        kwargs["url"] = url
    if collection is not None:
        kwargs["collection"] = collection
    if item is not None:
        kwargs["item"] = item
    if assets is not None:
        kwargs["assets"] = assets

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
    if isinstance(titiler_endpoint, str):
        r = requests.get(f"{titiler_endpoint}/stac/statistics", params=kwargs).json()
    else:
        r = requests.get(
            titiler_endpoint.url_for_stac_statistics(), params=kwargs
        ).json()

    return r

stac_tile(url=None, collection=None, item=None, assets=None, bands=None, titiler_endpoint=None, **kwargs)

Get a tile layer from a single SpatialTemporal Asset Catalog (STAC) item.

Parameters:

Name Type Description Default
url str

HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json

None
collection str

The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.

None
item str

The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.

None
assets str | list

The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].

None
bands list

A list of band names, e.g., ["SR_B7", "SR_B5", "SR_B4"]

None
titiler_endpoint str

TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "https://planetarycomputer.microsoft.com/api/data/v1", "planetary-computer", "pc". Defaults to None.

None

Returns:

Type Description
str

The STAC tile layer URL.

Source code in leafmap/stac.py
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
def stac_tile(
    url: str = None,
    collection: str = None,
    item: str = None,
    assets: Union[str, List] = None,
    bands: list = None,
    titiler_endpoint: Optional[str] = None,
    **kwargs,
) -> str:
    """Get a tile layer from a single SpatialTemporal Asset Catalog (STAC) item.

    Args:
        url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
        collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
        item (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
        assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
        bands (list): A list of band names, e.g., ["SR_B7", "SR_B5", "SR_B4"]
        titiler_endpoint (str, optional): TiTiler endpoint, e.g., "https://giswqs-titiler-endpoint.hf.space", "https://planetarycomputer.microsoft.com/api/data/v1", "planetary-computer", "pc". Defaults to None.

    Returns:
        The STAC tile layer URL.
    """
    import json

    if url is None and collection is None:
        raise ValueError("Either url or collection must be specified.")

    if collection is not None and titiler_endpoint is None:
        titiler_endpoint = "planetary-computer"

    if isinstance(url, pystac.Item):
        try:
            url = url.self_href
        except Exception as e:
            print(e)

    if url is not None:
        kwargs["url"] = url
    if collection is not None:
        kwargs["collection"] = collection
    if item is not None:
        kwargs["item"] = item

    if "palette" in kwargs:
        kwargs["colormap_name"] = kwargs["palette"].lower()
        del kwargs["palette"]

    if isinstance(bands, list) and len(set(bands)) == 1:
        bands = bands[0]

    if isinstance(assets, list) and len(set(assets)) == 1:
        assets = assets[0]

    titiler_endpoint = check_titiler_endpoint(titiler_endpoint)

    if "expression" in kwargs and ("asset_as_band" not in kwargs):
        kwargs["asset_as_band"] = True

    mosaic_json = False

    if isinstance(titiler_endpoint, PlanetaryComputerEndpoint):
        if isinstance(bands, str):
            bands = bands.split(",")
        if isinstance(assets, str):
            assets = assets.split(",")
        if assets is None and (bands is not None):
            assets = bands
        else:
            kwargs["bidx"] = bands

        kwargs["assets"] = assets

        if (
            (assets is not None)
            and ("asset_expression" not in kwargs)
            and ("expression" not in kwargs)
            and ("rescale" not in kwargs)
        ):
            try:
                stats = stac_stats(
                    collection=collection,
                    item=item,
                    assets=assets,
                    titiler_endpoint=titiler_endpoint,
                )
            except Exception as e:
                fallback_endpoint = "https://giswqs-titiler-endpoint.hf.space"
                stats = stac_stats(
                    collection=collection,
                    item=item,
                    assets=assets,
                    titiler_endpoint=fallback_endpoint,
                )

            if "detail" not in stats:
                try:
                    percentile_2 = min([stats[s]["percentile_2"] for s in stats])
                    percentile_98 = max([stats[s]["percentile_98"] for s in stats])
                except:
                    percentile_2 = min(
                        [
                            stats[s][list(stats[s].keys())[0]]["percentile_2"]
                            for s in stats
                        ]
                    )
                    percentile_98 = max(
                        [
                            stats[s][list(stats[s].keys())[0]]["percentile_98"]
                            for s in stats
                        ]
                    )
                kwargs["rescale"] = f"{percentile_2},{percentile_98}"

    else:
        data = requests.get(url).json()
        if "mosaicjson" in data:
            mosaic_json = True

        if isinstance(bands, str):
            bands = bands.split(",")
        if isinstance(assets, str):
            assets = assets.split(",")

        if assets is None:
            if bands is not None:
                assets = bands
            else:
                bnames = stac_bands(url)
                if isinstance(bnames, list):
                    if len(bnames) >= 3:
                        assets = bnames[0:3]
                    else:
                        assets = bnames[0]
                else:
                    assets = None

        else:
            if bands is not None:
                kwargs["asset_bidx"] = bands
        if assets is not None:
            kwargs["assets"] = assets

            if len(kwargs["assets"]) == 1 and ("colormap" not in kwargs):
                cog_url = get_cog_link_from_stac_item(url)
                colormap = _get_image_colormap(cog_url)
                if colormap is not None:
                    kwargs["colormap"] = colormap

        if (
            (assets is not None)
            and ("asset_expression" not in kwargs)
            and ("expression" not in kwargs)
            and ("rescale" not in kwargs)
            and ("colormap" not in kwargs)
        ):
            try:
                stats = stac_stats(
                    url=url,
                    assets=assets,
                    titiler_endpoint=titiler_endpoint,
                )
            except Exception as e:
                print(e)
                return None

            if "detail" not in stats:
                try:
                    percentile_2 = min([stats[s]["percentile_2"] for s in stats])
                    percentile_98 = max([stats[s]["percentile_98"] for s in stats])
                except:
                    percentile_2 = min(
                        [
                            stats[s][list(stats[s].keys())[0]]["percentile_2"]
                            for s in stats
                        ]
                    )
                    percentile_98 = max(
                        [
                            stats[s][list(stats[s].keys())[0]]["percentile_98"]
                            for s in stats
                        ]
                    )
                kwargs["rescale"] = f"{percentile_2},{percentile_98}"
            else:
                print(stats["detail"])  # When operation times out.

    TileMatrixSetId = "WebMercatorQuad"
    if "TileMatrixSetId" in kwargs.keys():
        TileMatrixSetId = kwargs["TileMatrixSetId"]
        kwargs.pop("TileMatrixSetId")

    if "colormap" in kwargs and isinstance(kwargs["colormap"], dict):
        kwargs["colormap"] = json.dumps(kwargs["colormap"])

    if mosaic_json:
        try:
            r = requests.get(
                f"{titiler_endpoint}/mosaicjson/{TileMatrixSetId}/tilejson.json",
                params=kwargs,
                timeout=10,
            ).json()
        except Exception as e:
            titiler_endpoint = "https://giswqs-titiler-endpoint.hf.space"
            r = requests.get(
                f"{titiler_endpoint}/mosaicjson/{TileMatrixSetId}/tilejson.json",
                params=kwargs,
                timeout=10,
            ).json()
    else:
        if isinstance(titiler_endpoint, str):
            try:
                r = requests.get(
                    f"{titiler_endpoint}/stac/{TileMatrixSetId}/tilejson.json",
                    params=kwargs,
                    timeout=10,
                ).json()
            except Exception as e:
                titiler_endpoint = "https://giswqs-titiler-endpoint.hf.space"
                r = requests.get(
                    f"{titiler_endpoint}/stac/{TileMatrixSetId}/tilejson.json",
                    params=kwargs,
                    timeout=10,
                ).json()
        else:
            r = requests.get(
                titiler_endpoint.url_for_stac_item(), params=kwargs, timeout=10
            ).json()

    # Check if the response contains tiles
    if "tiles" not in r:
        # Try to provide helpful error message from the API response
        if "detail" in r:
            error_msg = f"TiTiler endpoint error: {r['detail']}"
        elif isinstance(r, list) and len(r) > 0:
            # Handle validation errors (list of error dicts)
            if isinstance(r[0], dict) and "msg" in r[0]:
                errors = []
                for e in r:
                    loc = "->".join(str(x) for x in e.get("loc", []))
                    msg = e.get("msg", "")
                    errors.append(f"{loc}: {msg}")
                error_msg = f"TiTiler endpoint validation failed: {'; '.join(errors)}"
            else:
                error_msg = f"TiTiler endpoint returned error list: {r}"
        else:
            error_msg = f"TiTiler endpoint returned unexpected response (missing 'tiles' key): {r}"
        raise ValueError(error_msg)

    tiles = r["tiles"][0]

    # Convert 127.0.0.1 to localhost for Google Colab browser access
    if "google.colab" in sys.modules and "127.0.0.1" in tiles:
        tiles = tiles.replace("http://127.0.0.1", "https://localhost")

    return tiles

zarr_bounds(url, variable=None, titiler_endpoint=None, group=None, decode_times=False, **kwargs)

Get the bounds of a Zarr dataset.

Parameters:

Name Type Description Default
url str

HTTP URL to a Zarr dataset.

required
variable str

The variable name. Defaults to None.

None
titiler_endpoint str

TiTiler endpoint that supports xarray/Zarr. If not provided, the function first checks the TITILER_XARRAY_ENDPOINT environment variable; if that is not set, it falls back to the default endpoint returned by :func:check_titiler_endpoint.

None
group str

The Zarr group path within the dataset. Defaults to None.

None
decode_times bool

Whether to decode times in the dataset. Defaults to False.

False
**kwargs

Additional arguments to pass to the titiler endpoint.

{}

Returns:

Name Type Description
list list

Bounds as [minx, miny, maxx, maxy] in WGS84.

Source code in leafmap/stac.py
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
def zarr_bounds(
    url: str,
    variable: Optional[str] = None,
    titiler_endpoint: Optional[str] = None,
    group: Optional[str] = None,
    decode_times: bool = False,
    **kwargs,
) -> list:
    """Get the bounds of a Zarr dataset.

    Args:
        url (str): HTTP URL to a Zarr dataset.
        variable (str, optional): The variable name. Defaults to None.
        titiler_endpoint (str, optional): TiTiler endpoint that supports xarray/Zarr.
            If not provided, the function first checks the ``TITILER_XARRAY_ENDPOINT``
            environment variable; if that is not set, it falls back to the default
            endpoint returned by :func:`check_titiler_endpoint`.
        group (str, optional): The Zarr group path within the dataset.
            Defaults to None.
        decode_times (bool, optional): Whether to decode times in the dataset.
            Defaults to False.
        **kwargs: Additional arguments to pass to the titiler endpoint.

    Returns:
        list: Bounds as [minx, miny, maxx, maxy] in WGS84.
    """
    if os.environ.get("USE_MKDOCS") is not None:
        return None

    # Check for xarray-specific endpoint
    if titiler_endpoint is None:
        titiler_endpoint = os.environ.get("TITILER_XARRAY_ENDPOINT")

    if titiler_endpoint is None:
        titiler_endpoint = check_titiler_endpoint(titiler_endpoint)

    params = {"url": url, "decode_times": str(decode_times).lower()}
    if variable is not None:
        params["variable"] = variable
    if group is not None:
        params["group"] = group
    params.update(kwargs)

    try:
        # Use /info endpoint since /bounds may not exist in titiler-xarray
        r = requests.get(
            f"{titiler_endpoint}/md/info",
            params=params,
            timeout=30,
        ).json()
        return r.get("bounds", None)
    except Exception as e:
        print(f"Error getting Zarr bounds: {e}")
        return None

zarr_info(url, variable=None, titiler_endpoint=None, group=None, decode_times=False, **kwargs)

Get information about a Zarr dataset.

Parameters:

Name Type Description Default
url str

HTTP URL to a Zarr dataset.

required
variable str

The variable name. Required by titiler-xarray. Defaults to None.

None
titiler_endpoint str

TiTiler endpoint that supports xarray/Zarr. Defaults to "https://giswqs-titiler-endpoint.hf.space".

None
group str

The Zarr group path within the dataset. Defaults to None.

None
decode_times bool

Whether to decode times in the dataset. Defaults to False.

False
**kwargs

Additional arguments to pass to the titiler endpoint.

{}

Returns:

Name Type Description
dict dict

Information about the Zarr dataset including bounds, CRS, and variables.

Source code in leafmap/stac.py
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
def zarr_info(
    url: str,
    variable: Optional[str] = None,
    titiler_endpoint: Optional[str] = None,
    group: Optional[str] = None,
    decode_times: bool = False,
    **kwargs,
) -> dict:
    """Get information about a Zarr dataset.

    Args:
        url (str): HTTP URL to a Zarr dataset.
        variable (str, optional): The variable name. Required by titiler-xarray.
            Defaults to None.
        titiler_endpoint (str, optional): TiTiler endpoint that supports xarray/Zarr.
            Defaults to "https://giswqs-titiler-endpoint.hf.space".
        group (str, optional): The Zarr group path within the dataset.
            Defaults to None.
        decode_times (bool, optional): Whether to decode times in the dataset.
            Defaults to False.
        **kwargs: Additional arguments to pass to the titiler endpoint.

    Returns:
        dict: Information about the Zarr dataset including bounds, CRS, and variables.
    """
    if os.environ.get("USE_MKDOCS") is not None:
        return None

    # Check for xarray-specific endpoint
    if titiler_endpoint is None:
        titiler_endpoint = os.environ.get("TITILER_XARRAY_ENDPOINT")

    if titiler_endpoint is None:
        titiler_endpoint = check_titiler_endpoint(titiler_endpoint)

    params = {"url": url, "decode_times": str(decode_times).lower()}
    if variable is not None:
        params["variable"] = variable
    if group is not None:
        params["group"] = group
    params.update(kwargs)

    try:
        r = requests.get(
            f"{titiler_endpoint}/md/info",
            params=params,
            timeout=30,
        ).json()
        return r
    except Exception as e:
        print(f"Error getting Zarr info: {e}")
        return None

zarr_statistics(url, variable=None, titiler_endpoint=None, group=None, decode_times=False, **kwargs)

Get statistics for a Zarr dataset variable.

Parameters:

Name Type Description Default
url str

HTTP URL to a Zarr dataset.

required
variable str

The variable name. Required for multi-variable datasets.

None
titiler_endpoint str

TiTiler endpoint that supports xarray/Zarr. Defaults to "https://giswqs-titiler-endpoint.hf.space".

None
group str

The Zarr group path within the dataset. Defaults to None.

None
decode_times bool

Whether to decode times in the dataset. Defaults to False.

False
**kwargs

Additional arguments to pass to the titiler endpoint.

{}

Returns:

Name Type Description
dict dict

Statistics including min, max, mean, std, etc.

Source code in leafmap/stac.py
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
def zarr_statistics(
    url: str,
    variable: Optional[str] = None,
    titiler_endpoint: Optional[str] = None,
    group: Optional[str] = None,
    decode_times: bool = False,
    **kwargs,
) -> dict:
    """Get statistics for a Zarr dataset variable.

    Args:
        url (str): HTTP URL to a Zarr dataset.
        variable (str, optional): The variable name. Required for multi-variable datasets.
        titiler_endpoint (str, optional): TiTiler endpoint that supports xarray/Zarr.
            Defaults to "https://giswqs-titiler-endpoint.hf.space".
        group (str, optional): The Zarr group path within the dataset.
            Defaults to None.
        decode_times (bool, optional): Whether to decode times in the dataset.
            Defaults to False.
        **kwargs: Additional arguments to pass to the titiler endpoint.

    Returns:
        dict: Statistics including min, max, mean, std, etc.
    """
    if os.environ.get("USE_MKDOCS") is not None:
        return None

    # Check for xarray-specific endpoint
    if titiler_endpoint is None:
        titiler_endpoint = os.environ.get("TITILER_XARRAY_ENDPOINT")

    if titiler_endpoint is None:
        titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
    params = {"url": url, "decode_times": str(decode_times).lower()}
    if variable is not None:
        params["variable"] = variable
    if group is not None:
        params["group"] = group
    params.update(kwargs)

    try:
        r = requests.get(
            f"{titiler_endpoint}/md/statistics",
            params=params,
            timeout=30,
        ).json()
        return r
    except Exception as e:
        print(f"Error getting Zarr statistics: {e}")
        return None

zarr_tile(url, variable=None, titiler_endpoint=None, group=None, decode_times=False, time_index=0, **kwargs)

Get a tile layer URL from a Zarr dataset using titiler-xarray.

This function requires a TiTiler endpoint with titiler-xarray support. The default titiler endpoint does NOT support Zarr/xarray datasets. You need to either: 1. Set up your own titiler-xarray endpoint 2. Use leafmap.run_titiler_xarray() to start a local server

Parameters:

Name Type Description Default
url str

HTTP URL to a Zarr dataset, e.g., https://example.com/data.zarr or s3://bucket/data.zarr

required
variable str

The variable name to visualize. Required for multi-variable datasets. Defaults to None.

None
titiler_endpoint str

TiTiler endpoint that supports xarray/Zarr. Must have titiler-xarray installed. Defaults to environment variable TITILER_XARRAY_ENDPOINT or prompts user to start a local server.

None
group str

The Zarr group path within the dataset. Defaults to None.

None
decode_times bool

Whether to decode times in the dataset. Defaults to False.

False
time_index int

Index of the time dimension to visualize. Required for datasets with a time dimension. Defaults to 0 (first time step). Set to None to disable time selection (for datasets without time dimension).

0
**kwargs Any

Additional arguments to pass to the titiler endpoint. Common options include: - rescale (str): Comma-delimited Min,Max range (e.g., "0,255") - colormap_name (str): Name of a colormap (e.g., "viridis") - colormap (str): JSON encoded custom colormap - nodata (float): Nodata value - sel (str): Dimension selection in format "dim=value" (e.g., "time=0") - TileMatrixSetId (str): Tile matrix set ID (default: "WebMercatorQuad")

{}

Returns:

Name Type Description
str str

The Zarr tile layer URL, or None if the endpoint doesn't support Zarr.

Example

Start local titiler-xarray server first

endpoint = leafmap.run_titiler_xarray() url = "https://example.com/data.zarr" tile_url = zarr_tile(url, variable="temperature", titiler_endpoint=endpoint)

Source code in leafmap/stac.py
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
def zarr_tile(
    url: str,
    variable: Optional[str] = None,
    titiler_endpoint: Optional[str] = None,
    group: Optional[str] = None,
    decode_times: bool = False,
    time_index: Optional[int] = 0,
    **kwargs,
) -> str:
    """Get a tile layer URL from a Zarr dataset using titiler-xarray.

    This function requires a TiTiler endpoint with titiler-xarray support.
    The default titiler endpoint does NOT support Zarr/xarray datasets.
    You need to either:
    1. Set up your own titiler-xarray endpoint
    2. Use `leafmap.run_titiler_xarray()` to start a local server

    Args:
        url (str): HTTP URL to a Zarr dataset, e.g., https://example.com/data.zarr
            or s3://bucket/data.zarr
        variable (str, optional): The variable name to visualize. Required for
            multi-variable datasets. Defaults to None.
        titiler_endpoint (str, optional): TiTiler endpoint that supports xarray/Zarr.
            Must have titiler-xarray installed. Defaults to environment variable
            TITILER_XARRAY_ENDPOINT or prompts user to start a local server.
        group (str, optional): The Zarr group path within the dataset.
            Defaults to None.
        decode_times (bool, optional): Whether to decode times in the dataset.
            Defaults to False.
        time_index (int, optional): Index of the time dimension to visualize.
            Required for datasets with a time dimension. Defaults to 0 (first time step).
            Set to None to disable time selection (for datasets without time dimension).
        **kwargs (Any): Additional arguments to pass to the titiler endpoint.
            Common options include:
            - rescale (str): Comma-delimited Min,Max range (e.g., "0,255")
            - colormap_name (str): Name of a colormap (e.g., "viridis")
            - colormap (str): JSON encoded custom colormap
            - nodata (float): Nodata value
            - sel (str): Dimension selection in format "dim=value" (e.g., "time=0")
            - TileMatrixSetId (str): Tile matrix set ID (default: "WebMercatorQuad")

    Returns:
        str: The Zarr tile layer URL, or None if the endpoint doesn't support Zarr.

    Example:
        >>> # Start local titiler-xarray server first
        >>> endpoint = leafmap.run_titiler_xarray()
        >>> url = "https://example.com/data.zarr"
        >>> tile_url = zarr_tile(url, variable="temperature", titiler_endpoint=endpoint)
    """
    if os.environ.get("USE_MKDOCS") is not None:
        return None

    # Check for xarray-specific endpoint
    if titiler_endpoint is None:
        titiler_endpoint = os.environ.get("TITILER_XARRAY_ENDPOINT")

    if titiler_endpoint is None:
        titiler_endpoint = check_titiler_endpoint(titiler_endpoint)

    kwargs["url"] = url

    if variable is not None:
        kwargs["variable"] = variable

    if group is not None:
        kwargs["group"] = group

    kwargs["decode_times"] = str(decode_times).lower()

    # Add time selection if time_index is specified
    # This is required for datasets with a time dimension
    if time_index is not None and "sel" not in kwargs:
        kwargs["sel"] = f"time={time_index}"

    if "palette" in kwargs:
        kwargs["colormap_name"] = kwargs["palette"].lower()
        del kwargs["palette"]

    # Ensure colormap_name is lowercase (required by titiler)
    if "colormap_name" in kwargs and kwargs["colormap_name"]:
        kwargs["colormap_name"] = kwargs["colormap_name"].lower()

    TileMatrixSetId = "WebMercatorQuad"
    if "TileMatrixSetId" in kwargs:
        TileMatrixSetId = kwargs["TileMatrixSetId"]
        kwargs.pop("TileMatrixSetId")

    try:
        r = requests.get(
            f"{titiler_endpoint}/md/{TileMatrixSetId}/tilejson.json",
            params=kwargs,
            timeout=30,
        ).json()

        # Check for various error conditions
        if "detail" in r:
            detail = r["detail"]
            if detail == "Not Found":
                print(
                    "Error: The titiler endpoint does not support Zarr/xarray datasets.\n"
                    "The '/md/' endpoint is not available. Please:\n"
                    "  1. Use a titiler endpoint with titiler-xarray installed, or\n"
                    "  2. Start a local titiler-xarray server with: leafmap.run_titiler_xarray()\n"
                    "  3. Set TITILER_XARRAY_ENDPOINT environment variable"
                )
                return None
            else:
                # Handle validation errors or other API errors
                print(f"Error from titiler endpoint: {detail}")
                return None

        if "tiles" not in r:
            print(f"Unexpected response from titiler: {r}")
            return None

        tiles = r["tiles"][0]
        if titiler_endpoint.startswith("https://") and tiles.startswith("http://"):
            tiles = tiles.replace("http://", "https://")

        # Convert 127.0.0.1 to localhost for Google Colab browser access
        if "google.colab" in sys.modules and "127.0.0.1" in tiles:
            tiles = tiles.replace("http://127.0.0.1", "https://localhost")

        return tiles
    except KeyError as e:
        print(f"Error getting Zarr tile URL: missing key {e}")
        return None
    except Exception as e:
        print(f"Error getting Zarr tile URL: {e}")
        return None

zarr_variables(url, titiler_endpoint=None, group=None, decode_times=False, **kwargs)

Get the list of variables from a Zarr dataset.

Parameters:

Name Type Description Default
url str

HTTP URL to a Zarr dataset.

required
titiler_endpoint str

TiTiler endpoint that supports xarray/Zarr. Defaults to "https://giswqs-titiler-endpoint.hf.space".

None
group str

The Zarr group path within the dataset. Defaults to None.

None
decode_times bool

Whether to decode times in the dataset. Defaults to False.

False
**kwargs

Additional arguments to pass to the titiler endpoint.

{}

Returns:

Name Type Description
list list

List of variable names in the Zarr dataset.

Source code in leafmap/stac.py
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
def zarr_variables(
    url: str,
    titiler_endpoint: Optional[str] = None,
    group: Optional[str] = None,
    decode_times: bool = False,
    **kwargs,
) -> list:
    """Get the list of variables from a Zarr dataset.

    Args:
        url (str): HTTP URL to a Zarr dataset.
        titiler_endpoint (str, optional): TiTiler endpoint that supports xarray/Zarr.
            Defaults to "https://giswqs-titiler-endpoint.hf.space".
        group (str, optional): The Zarr group path within the dataset.
            Defaults to None.
        decode_times (bool, optional): Whether to decode times in the dataset.
            Defaults to False.
        **kwargs: Additional arguments to pass to the titiler endpoint.

    Returns:
        list: List of variable names in the Zarr dataset.
    """
    if os.environ.get("USE_MKDOCS") is not None:
        return None

    # Check for xarray-specific endpoint
    if titiler_endpoint is None:
        titiler_endpoint = os.environ.get("TITILER_XARRAY_ENDPOINT")

    if titiler_endpoint is None:
        titiler_endpoint = check_titiler_endpoint(titiler_endpoint)

    params = {"url": url, "decode_times": str(decode_times).lower()}
    if group is not None:
        params["group"] = group
    params.update(kwargs)

    try:
        r = requests.get(
            f"{titiler_endpoint}/md/variables",
            params=params,
            timeout=30,
        ).json()
        return r
    except Exception as e:
        print(f"Error getting Zarr variables: {e}")
        return None