download module¶
leafmap.download
¶
This module provides functions to download data, including NAIP imagery and building data from Overture Maps.
convert_vector_format(input_file, output_format='geojson', filter_expression=None)
¶
Convert the downloaded data to a different format or filter it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_file
|
str
|
Path to the input file. |
required |
output_format
|
str
|
Format to convert to, one of "geojson", "parquet", "shapefile", "csv". |
'geojson'
|
filter_expression
|
Optional[str]
|
Optional GeoDataFrame query expression to filter the data. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Path to the converted file. |
download_naip(bbox, output_dir, year=None, max_items=10, overwrite=False, preview=False, **kwargs)
¶
Download NAIP imagery from Planetary Computer based on a bounding box.
This function searches for NAIP (National Agriculture Imagery Program) imagery from Microsoft's Planetary Computer that intersects with the specified bounding box. It downloads the imagery and saves it as GeoTIFF files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Tuple[float, float, float, float]
|
Bounding box in the format (min_lon, min_lat, max_lon, max_lat) in WGS84 coordinates. |
required |
output_dir
|
str
|
Directory to save the downloaded imagery. |
required |
year
|
Optional[int]
|
Specific year of NAIP imagery to download (e.g., 2020). If None, returns imagery from all available years. |
None
|
max_items
|
int
|
Maximum number of items to download. |
10
|
overwrite
|
bool
|
If True, overwrite existing files with the same name. |
False
|
preview
|
bool
|
If True, display a preview of the downloaded imagery. |
False
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List of downloaded file paths. |
Raises:
| Type | Description |
|---|---|
Exception
|
If there is an error downloading or saving the imagery. |
download_overture_buildings(bbox, output=None, overture_type='building', **kwargs)
¶
Download building data from Overture Maps for a given bounding box using the overturemaps CLI tool.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Tuple[float, float, float, float]
|
Bounding box in the format (min_lon, min_lat, max_lon, max_lat) in WGS84 coordinates. |
required |
output
|
str
|
Path to save the output file. |
None
|
overture_type
|
str
|
The Overture Maps data type to download (building, place, etc.). |
'building'
|
Returns:
| Type | Description |
|---|---|
str
|
Path to the output file. |
download_pc_stac_item(item_url, bands=None, output_dir=None, show_progress=True, merge_bands=False, merged_filename=None, overwrite=False, cell_size=None)
¶
Downloads a STAC item from Microsoft Planetary Computer with specified bands.
This function fetches a STAC item by URL, signs the assets using Planetary Computer credentials, and downloads the specified bands with a progress bar. Can optionally merge bands into a single multi-band GeoTIFF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item_url
|
str
|
The URL of the STAC item to download. |
required |
bands
|
list
|
List of specific bands to download (e.g., ['B01', 'B02']). If None, all available bands will be downloaded. |
None
|
output_dir
|
str
|
Directory to save downloaded bands. If None, bands are returned as xarray DataArrays. |
None
|
show_progress
|
bool
|
Whether to display a progress bar. Default is True. |
True
|
merge_bands
|
bool
|
Whether to merge downloaded bands into a single multi-band GeoTIFF file. Default is False. |
False
|
merged_filename
|
str
|
Filename for the merged bands. If None and merge_bands is True, uses "{item_id}_merged.tif". |
None
|
overwrite
|
bool
|
Whether to overwrite existing files. Default is False. |
False
|
cell_size
|
float
|
Resolution in meters for the merged output. If None, uses the resolution of the first band. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dictionary mapping band names to their corresponding xarray DataArrays or file paths if output_dir is provided. If merge_bands is True, also includes a 'merged' key with the path to the merged file. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the item cannot be retrieved or a requested band is not available. |
download_with_progress(url, output_path)
¶
Download a file with a progress bar.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL of the file to download. |
required |
output_path
|
str
|
Path where the file will be saved. |
required |
extract_building_stats(data)
¶
Extract statistics from the building data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
str
|
Path to the GeoJSON file or GeoDataFrame containing building data. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with statistics. |
get_all_overture_types()
¶
Get a list of all available Overture Maps data types.
Returns:
| Name | Type | Description |
|---|---|---|
list |
List of available Overture Maps data types. |
get_overture_data(overture_type, bbox=None, columns=None, output=None, **kwargs)
¶
Fetches overture data and returns it as a GeoDataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
overture_type
|
str
|
The type of overture data to fetch.It can be one of the following: address|building|building_part|division|division_area|division_boundary|place| segment|connector|infrastructure|land|land_cover|land_use|water |
required |
bbox
|
Tuple[float, float, float, float]
|
The bounding box to filter the data. Defaults to None. |
None
|
columns
|
List[str]
|
The columns to include in the output. Defaults to None. |
None
|
output
|
str
|
The file path to save the output GeoDataFrame. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
gpd.GeoDataFrame: The fetched overture data as a GeoDataFrame. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If the overture package is not installed. |
get_overture_latest_release(patch=True)
¶
Retrieves the value of the 'latest' key from the Overture Maps release JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patch
|
bool
|
If True, returns the full version string (e.g., "2025-02-19.0"). |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The value of the 'latest' key from the releases.json file. |
Raises:
| Type | Description |
|---|---|
RequestException
|
If there's an issue with the HTTP request. |
KeyError
|
If the 'latest' key is not found in the JSON data. |
JSONDecodeError
|
If the response cannot be parsed as JSON. |
json_serializable(obj)
¶
Convert NumPy types to native Python types for JSON serialization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
Any object to convert. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
JSON serializable version of the object. |
pc_collection_list(endpoint='https://planetarycomputer.microsoft.com/api/stac/v1', detailed=False, filter_by=None, sort_by='id')
¶
Retrieves and displays the list of available collections from Planetary Computer.
This function connects to the Planetary Computer STAC API and retrieves the list of all available collections, with options to filter and sort the results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
endpoint
|
str
|
STAC API endpoint URL. Defaults to "https://planetarycomputer.microsoft.com/api/stac/v1". |
'https://planetarycomputer.microsoft.com/api/stac/v1'
|
detailed
|
bool
|
Whether to return detailed information for each collection. If False, returns only basic info. Defaults to False. |
False
|
filter_by
|
dict
|
Dictionary of field:value pairs to filter collections. For example, {"license": "CC-BY-4.0"}. Defaults to None. |
None
|
sort_by
|
str
|
Field to sort the collections by. Defaults to "id". |
'id'
|
Returns:
| Type | Description |
|---|---|
|
pandas.DataFrame: DataFrame containing collection information. |
Raises:
| Type | Description |
|---|---|
ConnectionError
|
If there's an issue connecting to the API. |
pc_item_asset_list(item)
¶
Retrieve the list of asset keys from a STAC item in the Planetary Computer catalog.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
str
|
The URL of the STAC item. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list of asset keys available in the signed STAC item. |
pc_stac_download(items, output_dir='.', assets=None, max_workers=4, skip_existing=True)
¶
Download assets from STAC items retrieved from the Planetary Computer.
This function downloads specified assets from a list of STAC items to the specified output directory. It supports parallel downloads and can skip already downloaded files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list or Item
|
STAC Item object or list of STAC Item objects. |
required |
output_dir
|
str
|
Directory where assets will be saved. Defaults to current directory. |
'.'
|
assets
|
list
|
List of asset keys to download. If None, downloads all available assets. Defaults to None. |
None
|
max_workers
|
int
|
Maximum number of concurrent download threads. Defaults to 4. |
4
|
skip_existing
|
bool
|
Skip download if the file already exists. Defaults to True. |
True
|
sign_urls
|
bool
|
Whether to sign URLs for authenticated access. Defaults to True. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dictionary mapping STAC item IDs to dictionaries of their downloaded assets {asset_key: file_path}. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If items is not a STAC Item or list of STAC Items. |
IOError
|
If there's an error writing the downloaded assets to disk. |
pc_stac_search(collection, bbox=None, time_range=None, query=None, limit=10, max_items=None, endpoint='https://planetarycomputer.microsoft.com/api/stac/v1')
¶
Search for STAC items in the Planetary Computer catalog.
This function queries the Planetary Computer STAC API to find items matching the specified criteria, including collection, bounding box, time range, and additional query parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection
|
str
|
The STAC collection ID to search within. |
required |
bbox
|
list
|
Bounding box coordinates [west, south, east, north]. Defaults to None. |
None
|
time_range
|
str or tuple
|
Time range as a string "start/end" or a tuple of (start, end) datetime objects. Defaults to None. |
None
|
query
|
dict
|
Additional query parameters for filtering. Defaults to None. |
None
|
limit
|
int
|
Number of items to return per page. Defaults to 10. |
10
|
max_items
|
int
|
Maximum total number of items to return. Defaults to None (returns all matching items). |
None
|
endpoint
|
str
|
STAC API endpoint URL. Defaults to "https://planetarycomputer.microsoft.com/api/stac/v1". |
'https://planetarycomputer.microsoft.com/api/stac/v1'
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
List of STAC Item objects matching the search criteria. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If invalid parameters are provided. |
ConnectionError
|
If there's an issue connecting to the API. |
preview_raster(data, title=None)
¶
Display a preview of the downloaded imagery.
This function creates a visualization of the downloaded NAIP imagery by converting it to an RGB array and displaying it with matplotlib.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The raster data as a rioxarray object. |
required |
title
|
str
|
The title for the preview plot. |
None
|
read_pc_item_asset(item, asset, output=None, as_cog=True, **kwargs)
¶
Read a specific asset from a STAC item in the Planetary Computer catalog.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
str
|
The URL of the STAC item. |
required |
asset
|
str
|
The key of the asset to read. |
required |
output
|
str
|
If specified, the path to save the asset as a raster file. |
None
|
as_cog
|
bool
|
If True, save the asset as a Cloud Optimized GeoTIFF (COG). |
True
|
Returns:
| Type | Description |
|---|---|
|
xarray.DataArray: The data array for the specified asset. |
sign_pc_item(item, asset=None, return_href=True)
¶
Sign a STAC item using Planetary Computer credentials.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
Item or str
|
The STAC item to sign, or its URL. |
required |
Returns:
| Type | Description |
|---|---|
|
pystac.Item: The signed STAC item with authenticated asset URLs. |
view_pc_items(urls=None, collection=None, items=None, assets=None, bands=None, titiler_endpoint=None, attribution='Planetary Computer', opacity=1.0, shown=True, fit_bounds=True, layer_index=None, backend='folium', basemap=None, map_args=None, **kwargs)
¶
Visualize multiple STAC items from the Planetary Computer on an interactive map.
This function allows users to display multiple STAC items on a map using either
the folium or ipyleaflet backend. It supports adding basemaps, configuring
map options, and customizing the visualization of the STAC items.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
urls
|
list
|
List of URLs of the STAC items to visualize. Defaults to None. |
None
|
collection
|
str
|
The collection ID of the STAC items. Defaults to None. |
None
|
items
|
list or str
|
List of STAC items or their IDs. Defaults to None. |
None
|
assets
|
list
|
List of asset keys to visualize. Defaults to None. |
None
|
bands
|
list
|
List of specific bands to visualize. Defaults to None. |
None
|
titiler_endpoint
|
str
|
URL of the Titiler endpoint for rendering. Defaults to None. |
None
|
attribution
|
str
|
Attribution text for the layers. Defaults to "Planetary Computer". |
'Planetary Computer'
|
opacity
|
float
|
Opacity of the layers (0.0 to 1.0). Defaults to 1.0. |
1.0
|
shown
|
bool
|
Whether the layers are visible by default. Defaults to True. |
True
|
fit_bounds
|
bool
|
Whether to fit the map bounds to the layers. Defaults to True. |
True
|
layer_index
|
int
|
Index of the layers in the map's layer stack. Defaults to None. |
None
|
backend
|
str
|
Map backend to use ('folium' or 'ipyleaflet'). Defaults to "folium". |
'folium'
|
basemap
|
str
|
Name of the basemap to add to the map. Defaults to None. |
None
|
map_args
|
dict
|
Additional arguments for configuring the map. Defaults to None. |
None
|
**kwargs
|
Additional keyword arguments passed to the |
{}
|
Returns:
| Type | Description |
|---|---|
|
leafmap.Map: An interactive map with the STAC items visualized. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unsupported backend is specified. |