Skip to content

toolbar module

leafmap.toolbar

Module for dealing with the toolbar.

GoogleMapsTileProvider

Bases: TileProvider

Google Maps TileProvider.

__init__(map_type='roadmap', language='en-Us', region='US', api_key=None, **kwargs)

Generates Google Map tiles using the provided parameters. To get an API key and enable Map Tiles API, visit https://developers.google.com/maps/get-started#create-project. You can set the API key using the environment variable GOOGLE_MAPS_API_KEY or by passing it as an argument.

Parameters:

Name Type Description Default
map_type str

The type of map to generate. Options are 'roadmap', 'satellite', 'terrain', 'hybrid', 'traffic', 'streetview'. Defaults to 'roadmap'.

'roadmap'
language str

An IETF language tag that specifies the language used to display information on the tiles, such as 'zh-Cn'. Defaults to 'en-Us'.

'en-Us'
region str

A Common Locale Data Repository region identifier (two uppercase letters) that represents the physical location of the user. Defaults to 'US'.

'US'
api_key str

The API key to use for the Google Maps API. If not provided, it will try to get it from the environment or Colab user data with the key 'GOOGLE_MAPS_API_KEY'. Defaults to None.

None
**kwargs Any

Additional parameters to pass to the map generation. For more info, visit https://bit.ly/3UhbZKU

{}

Raises:

Type Description
ValueError

If the API key is not provided and cannot be found in the environment or Colab user data.

ValueError

If the map_type is not one of the allowed types.

Example

from leafmap.basemaps import GoogleMapsTileProvider m = leafmap.Map() basemap = GoogleMapsTileProvider(map_type='roadmap', language="en-Us", region="US", scale="scaleFactor2x", highDpi=True) m.add_basemap(basemap)

PlanetaryComputerEndpoint

Bases: TitilerEndpoint

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

__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'

The_national_map_USGS

The national map is a collection of topological datasets, maintained by the USGS.

It provides an API endpoint which can be used to find downloadable links for the products offered. - Full description of datasets available can retrieved. This consists of metadata such as detail description and publication dates. - A wide range of dataformats are available

This class is a tiny wrapper to find and download files using the API.

More complete documentation for the API can be found at https://apps.nationalmap.gov/tnmaccess/#/

datasets property

Returns a list of dataset tags (most common human readable self description for specific datasets).

datasets_full property

Full description of datasets provided. Returns a JSON or empty list.

prodFormats property

Return all datatypes available in any of the collections. Note that "All" is only peculiar to one dataset.

download_tiles(region=None, out_dir=None, download_args={}, geopandas_args={}, API={})

Download the US National Elevation Datasets (NED) for a region.

Parameters:

Name Type Description Default
region str | list

An URL|filepath to a vector dataset Or a list of bounds in the form of [minx, miny, maxx, maxy]. Alternatively you could use API parameters such as polygon or bbox.

None
out_dir str

The directory to download the files to. Defaults to None, which uses the current working directory.

None
download_args dict

A dictionary of arguments to pass to the download_file function. Defaults to {}.

{}
geopandas_args dict

A dictionary of arguments to pass to the geopandas.read_file() function. Used for reading a region URL|filepath.

{}
API dict

A dictionary of arguments to pass to the self.find_details() function. Exposes most of the documented API. Defaults to {}.

{}

Returns:

Type Description
None

None

find_details(bbox=None, polygon=None, datasets=None, prodFormats=None, prodExtents=None, q=None, dateType=None, start=None, end=None, offset=0, max=None, outputFormat='JSON', polyType=None, polyCode=None, extentQuery=None)

Possible search parameters (kwargs) support by API

Parameter Values Description


bbox 'minx, miny, maxx, maxy' Geographic longitude/latitude values expressed in decimal degrees in a comma-delimited list. polygon '[x,y x,y x,y x,y x,y]' Polygon, longitude/latitude values expressed in decimal degrees in a space-delimited list. datasets See: Datasets (Optional) Dataset tag name (sbDatasetTag) From https://apps.nationalmap.gov/tnmaccess/#/product prodFormats See: Product Formats (Optional) Dataset-specific format

Product Extents (Optional)

Dataset-specific extent

q free text Text input which can be used to filter by product titles and text descriptions. dateType dateCreated | lastUpdated | Publication Type of date to search by. start 'YYYY-MM-DD' Start date end 'YYYY-MM-DD' End date (required if start date is provided) offset integer Offset into paginated results - default=0 max integer Number of results returned outputFormat JSON | CSV | pjson Default=JSON polyType state | huc2 | huc4 | huc8 Well Known Polygon Type. Use this parameter to deliver data by state or HUC (hydrologic unit codes defined by the Watershed Boundary Dataset/WBD) polyCode state FIPS code or huc number Well Known Polygon Code. This value needs to coordinate with the polyType parameter. extentQuery integer A Polygon code in the science base system, typically from an uploaded shapefile

find_tiles(region=None, return_type='list', geopandas_args={}, API={})

Find a list of downloadable files.

Parameters:

Name Type Description Default
region str | list

An URL|filepath to a vector dataset Or a list of bounds in the form of [minx, miny, maxx, maxy]. Alternatively you could use API parameters such as polygon or bbox.

None
return_type str

list | dict. Defaults to list. Changes the return output type and content.

'list'
geopandas_args dict

A dictionary of arguments to pass to the geopandas.read_file() function. Used for reading a region URL|filepath.

{}
API dict

A dictionary of arguments to pass to the self.find_details() function. Exposes most of the documented API parameters. Defaults to {}.

{}

Returns:

Type Description
Union[List[str], Dict]

A list of download URLs if return_type is 'list', otherwise a dictionary with URLs and related metadata.

parse_region(region, geopandas_args={})

Translate a Vector dataset to its bounding box.

Parameters:

Name Type Description Default
region str | list

an URL|filepath to a vector dataset to a polygon

required
geopandas_args dict

A dictionary of arguments to pass to the geopandas.read_file() function. Used for reading a region URL|filepath.

{}

TitilerCMREndpoint

This class contains the methods for the TiTiler CMR endpoint.

__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'

url_for_statistics()

Get the URL for the statistics endpoint.

Returns:

Name Type Description
str

The statistics endpoint URL.

url_for_tilejson()

Get the URL for the TileJSON endpoint.

Returns:

Name Type Description
str

The TileJSON endpoint URL.

url_for_timeseries()

Get the URL for the time series endpoint.

Returns:

Name Type Description
str

The time series endpoint URL.

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.

url_for_timeseries_statistics()

Get the URL for the time series statistics endpoint.

Returns:

Name Type Description
str

The time series statistics endpoint URL.

url_for_timeseries_tilejson()

Get the URL for the time series TileJSON endpoint.

Returns:

Name Type Description
str

The time series TileJSON endpoint URL.

TitilerEndpoint

This class contains the methods for the titiler endpoint.

__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://titiler.opengeos.org".

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'

WhiteboxTools

Bases: WhiteboxTools

This class inherits the whitebox WhiteboxTools class.

add_crs(filename, epsg)

Add a CRS to a raster dataset.

Parameters:

Name Type Description Default
filename str

The filename of the raster dataset.

required
epsg int | str

The EPSG code of the CRS.

required

add_image_to_gif(in_gif, out_gif, in_image, xy=None, image_size=(80, 80), circle_mask=False)

Adds an image logo to a GIF image.

Parameters:

Name Type Description Default
in_gif str

Input file path to the GIF image.

required
out_gif str

Output file path to the GIF image.

required
in_image str

Input file path to the image.

required
xy tuple

Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None.

None
image_size tuple

Resize image. Defaults to (80, 80).

(80, 80)
circle_mask bool

Whether to apply a circle mask to the image. This only works with non-png images. Defaults to False.

False

add_mask_to_image(image, mask, output, color='red')

Overlay a binary mask (e.g., roads, building footprints, etc) on an image. Credits to Xingjian Shi for the sample code.

Parameters:

Name Type Description Default
image str

A local path or HTTP URL to an image.

required
mask str

A local path or HTTP URL to a binary mask.

required
output str

A local path to the output image.

required
color str

Color of the mask. Defaults to 'red'.

'red'

Raises:

Type Description
ImportError

If rasterio and detectron2 are not installed.

add_progress_bar_to_gif(in_gif, out_gif, progress_bar_color='blue', progress_bar_height=5, duration=100, loop=0)

Adds a progress bar to a GIF image.

Parameters:

Name Type Description Default
in_gif str

The file path to the input GIF image.

required
out_gif str

The file path to the output GIF image.

required
progress_bar_color str

Color for the progress bar. Defaults to 'white'.

'blue'
progress_bar_height int

Height of the progress bar. Defaults to 5.

5
duration int

controls how long each frame will be displayed for, in milliseconds. It is the inverse of the frame rate. Setting it to 100 milliseconds gives 10 frames per second. You can decrease the duration to give a smoother animation. Defaults to 100.

100
loop int

controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0.

0

add_text_to_gif(in_gif, out_gif, xy=None, text_sequence=None, font_type='arial.ttf', font_size=20, font_color='#000000', add_progress_bar=True, progress_bar_color='white', progress_bar_height=5, duration=100, loop=0)

Adds animated text to a GIF image.

Parameters:

Name Type Description Default
in_gif str

The file path to the input GIF image.

required
out_gif str

The file path to the output GIF image.

required
xy tuple

Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None.

None
text_sequence (int, str, list)

Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None.

None
font_type str

Font type. Defaults to "arial.ttf".

'arial.ttf'
font_size int

Font size. Defaults to 20.

20
font_color str

Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'.

'#000000'
add_progress_bar bool

Whether to add a progress bar at the bottom of the GIF. Defaults to True.

True
progress_bar_color str

Color for the progress bar. Defaults to 'white'.

'white'
progress_bar_height int

Height of the progress bar. Defaults to 5.

5
duration int

controls how long each frame will be displayed for, in milliseconds. It is the inverse of the frame rate. Setting it to 100 milliseconds gives 10 frames per second. You can decrease the duration to give a smoother animation.. Defaults to 100.

100
loop int

controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0.

0

add_unique_class(data, column, class_column='class', mapping=None)

Add a unique integer class column to a vector dataset based on an existing column.

Parameters:

Name Type Description Default
data str or GeoDataFrame

Input vector data as file path or GeoDataFrame.

required
column str

The column name used for generating unique classes.

required
class_column str

The name of the new column to store integer classes. Default is "class".

'class'
mapping dict

A dictionary mapping original values to integer classes. If not provided, a mapping will be generated automatically starting from 1.

None

Returns:

Type Description
GeoDataFrame

The updated GeoDataFrame with the new class column.

adjust_longitude(in_fc)

Adjusts longitude if it is less than -180 or greater than 180.

Parameters:

Name Type Description Default
in_fc dict

The input dictionary containing coordinates.

required

Returns:

Type Description
Optional[dict]

A dictionary containing the converted longitudes.

arc_active_map()

Get the active map in ArcGIS Pro.

Returns:

Type Description
Optional[Any]

The active map in ArcGIS Pro.

arc_active_view()

Get the active view in ArcGIS Pro.

Returns:

Type Description
Optional[Any]

The active view in ArcGIS Pro.

arc_add_layer(url, name=None, shown=True, opacity=1.0)

Add a layer to the active map in ArcGIS Pro.

Parameters:

Name Type Description Default
url str

The URL of the tile layer to add.

required
name str

The name of the layer. Defaults to None.

None
shown bool

Whether the layer is shown. Defaults to True.

True
opacity float

The opacity of the layer. Defaults to 1.0.

1.0

arc_zoom_to_bounds(bounds)

Zoom to a bounding box.

Parameters:

Name Type Description Default
bounds list

The bounding box to zoom to in the form [xmin, ymin, xmax, ymax] or [(ymin, xmin), (ymax, xmax)].

required

Raises:

Type Description
ValueError

description

arc_zoom_to_extent(xmin, ymin, xmax, ymax)

Zoom to an extent in ArcGIS Pro.

Parameters:

Name Type Description Default
xmin float

The minimum x value of the extent.

required
ymin float

The minimum y value of the extent.

required
xmax float

The maximum x value of the extent.

required
ymax float

The maximum y value of the extent.

required

array_to_image(array, output=None, source=None, dtype=None, compress='deflate', transpose=True, cellsize=None, crs=None, transform=None, driver='COG', colormap=None, **kwargs)

Save a NumPy array as a GeoTIFF using the projection information from an existing GeoTIFF file.

Parameters:

Name Type Description Default
array ndarray

The NumPy array to be saved as a GeoTIFF.

required
output str

The path to the output image. If None, a temporary file will be created. Defaults to None.

None
source str

The path to an existing GeoTIFF file with map projection information. Defaults to None.

None
dtype dtype

The data type of the output array. Defaults to None.

None
compress str

The compression method. Can be one of the following: "deflate", "lzw", "packbits", "jpeg". Defaults to "deflate".

'deflate'
transpose bool

Whether to transpose the array from (bands, rows, columns) to (rows, columns, bands). Defaults to True.

True
cellsize float

The resolution of the output image in meters. Defaults to None.

None
crs str

The CRS of the output image. Defaults to None.

None
transform tuple

The affine transformation matrix, can be rio.transform() or a tuple like (0.5, 0.0, -180.25, 0.0, -0.5, 83.780361). Defaults to None.

None
driver str

The driver to use for creating the output file, such as 'GTiff'. Defaults to "COG".

'COG'
colormap dict

A dictionary defining the colormap (value: (R, G, B, A)).

None
**kwargs Any

Additional keyword arguments to be passed to the rasterio.open() function.

{}

array_to_memory_file(array, source=None, dtype=None, compress='deflate', transpose=True, cellsize=None, crs=None, transform=None, driver='COG', colormap=None, **kwargs)

Convert a NumPy array to a memory file.

Parameters:

Name Type Description Default
array ndarray

The input NumPy array.

required
source str

Path to the source file to extract metadata from. Defaults to None.

None
dtype str

The desired data type of the array. Defaults to None.

None
compress str

The compression method for the output file. Defaults to "deflate".

'deflate'
transpose bool

Whether to transpose the array from (bands, rows, columns) to (rows, columns, bands). Defaults to True.

True
cellsize float

The cell size of the array if source is not provided. Defaults to None.

None
crs str

The coordinate reference system of the array if source is not provided. Defaults to None.

None
transform tuple

The affine transformation matrix if source is not provided. Can be rio.transform() or a tuple like (0.5, 0.0, -180.25, 0.0, -0.5, 83.780361). Defaults to None.

None
driver str

The driver to use for creating the output file, such as 'GTiff'. Defaults to "COG".

'COG'
colormap dict

A dictionary defining the colormap (value: (R, G, B, A)).

None
**kwargs Any

Additional keyword arguments to be passed to the rasterio.open() function.

{}

Returns:

Type Description
Any

The rasterio dataset reader object for the converted array.

assign_continuous_colors(df, column, cmap=None, colors=None, labels=None, scheme='Quantiles', k=5, legend_kwds=None, classification_kwds=None, to_rgb=True, return_type='array', return_legend=False)

Assigns continuous colors to a DataFrame column based on a specified scheme.

Parameters:

Name Type Description Default
df DataFrame

A pandas DataFrame.

required
column str

The name of the column to assign colors.

required
cmap str

The name of the colormap to use.

None
colors list

A list of custom colors.

None
labels list

A list of custom labels for the legend.

None
scheme str

The scheme for classifying the data. Default is 'Quantiles'.

'Quantiles'
k int

The number of classes for classification.

5
legend_kwds dict

Additional keyword arguments for configuring the legend.

None
classification_kwds dict

Additional keyword arguments for configuring the classification.

None
to_rgb bool

Whether to convert colors to RGB values. Default is True.

True
return_type str

The type of the returned values. Default is 'array'.

'array'
return_legend bool

Whether to return the legend. Default is False.

False

Returns:

Type Description
Union[ndarray, Tuple[ndarray, dict]]

The assigned colors as a numpy array or a tuple containing the colors and the legend, depending on the value of return_legend.

assign_discrete_colors(df, column, cmap, to_rgb=True, return_type='array')

Assigns unique colors to each category in a categorical column of a dataframe.

Parameters:

Name Type Description Default
df DataFrame

The input dataframe.

required
column str

The name of the categorical column.

required
cmap dict

A dictionary mapping categories to colors.

required
to_rgb bool

Whether to convert the colors to RGB values. Defaults to True.

True
return_type str

The type of the returned values. Can be 'list' or 'array'. Defaults to 'array'.

'array'

Returns:

Type Description
Union[List, ndarray]

A list of colors for each category in the categorical column.

basemap_xyz_tiles()

Returns a dictionary containing a set of basemaps that are XYZ tile layers.

Returns:

Type Description
Dict[str, Any]

A dictionary of XYZ tile layers.

bbox_to_gdf(bbox, crs='epsg:4326')

Convert a bounding box to a GeoPandas GeoDataFrame.

Parameters:

Name Type Description Default
bbox list

A bounding box in the format of [minx, miny, maxx, maxy].

required
crs str

The CRS of the bounding box. Defaults to 'epsg:4326'.

'epsg:4326'

Returns:

Type Description
GeoDataFrame

A GeoDataFrame with a single polygon.

bbox_to_geojson(bounds)

Convert coordinates of a bounding box to a geojson.

Parameters:

Name Type Description Default
bounds list | tuple

A list of coordinates representing [left, bottom, right, top] or m.bounds.

required

Returns:

Type Description
dict

A geojson feature.

bbox_to_polygon(bbox)

Convert a bounding box to a shapely Polygon.

Parameters:

Name Type Description Default
bbox list

A bounding box in the format of [minx, miny, maxx, maxy].

required

Returns:

Type Description
Any

A shapely Polygon.

blend_images(img1, img2, alpha=0.5, output=False, show=True, figsize=(12, 10), axis='off', **kwargs)

Blends two images together using the addWeighted function from the OpenCV library.

Parameters:

Name Type Description Default
img1 ndarray

The first input image on top represented as a NumPy array.

required
img2 ndarray

The second input image at the bottom represented as a NumPy array.

required
alpha float

The weighting factor for the first image in the blend. By default, this is set to 0.5.

0.5
output str

The path to the output image. Defaults to False.

False
show bool

Whether to display the blended image. Defaults to True.

True
figsize tuple

The size of the figure. Defaults to (12, 10).

(12, 10)
axis str

The axis of the figure. Defaults to "off".

'off'
**kwargs Any

Additional keyword arguments to pass to the cv2.addWeighted() function.

{}

Returns:

Type Description
Any

The blended image as a NumPy array.

bounds_to_xy_range(bounds)

Convert bounds to x and y range to be used as input to bokeh map.

Parameters:

Name Type Description Default
bounds Union[List[Union[Tuple[float, float], float]], Tuple[float, float, float, float]]

A list of bounds in the form [(south, west), (north, east)] or [xmin, ymin, xmax, ymax].

required

Returns:

Type Description
Tuple[Tuple[float, float], Tuple[float, float]]

Tuple[Tuple[float, float], Tuple[float, float]]: A tuple of (x_range, y_range).

census_widget(m)

Widget for adding US Census data.

Parameters:

Name Type Description Default
m Map

The leaflet Map object. Defaults to None.

required

Returns:

Name Type Description
ipywidgets Widget

The tool GUI widget.

center_zoom_to_xy_range(center, zoom)

Convert center and zoom to x and y range to be used as input to bokeh map.

Parameters:

Name Type Description Default
center tuple

A tuple of (latitude, longitude).

required
zoom int

The zoom level.

required

Returns:

Type Description
Tuple[Tuple[float, float], Tuple[float, float]]

A tuple of (x_range, y_range).

cesium_to_streamlit(html, width=800, height=600, responsive=True, scrolling=False, token_name=None, token_value=None, **kwargs)

Renders an cesium HTML file in a Streamlit app. This method is a static Streamlit Component, meaning, no information is passed back from Leaflet on browser interaction.

Parameters:

Name Type Description Default
html str

The HTML file to render. It can a local file path or a URL.

required
width int

Width of the map. Defaults to 800.

800
height int

Height of the map. Defaults to 600.

600
responsive bool

Whether to make the map responsive. Defaults to True.

True
scrolling bool

Whether to allow the map to scroll. Defaults to False.

False
token_name str

The name of the token in the HTML file to be replaced. Defaults to None.

None
token_value str

The value of the token to pass to the HTML file. Defaults to None.

None

Returns:

Type Description
Any

A Streamlit components.html object.

change_basemap(m, position='topright')

Widget for changing basemaps.

Parameters:

Name Type Description Default
m object

leafmap.Map.

required

check_cmap(cmap)

Check the colormap and return a list of colors.

Parameters:

Name Type Description Default
cmap str | list | Box

The colormap to check.

required

Returns:

Type Description
List[str]

A list of colors.

check_color(in_color)

Checks the input color and returns the corresponding hex color code.

Parameters:

Name Type Description Default
in_color str or tuple or list

It can be a string (e.g., 'red', '#ffff00', 'ffff00', 'ff0') or RGB tuple/list (e.g., (255, 127, 0)).

required

Returns:

Type Description
str

A hex color code.

check_dir(dir_path, make_dirs=True)

Checks if a directory exists and creates it if it does not.

Parameters:

Name Type Description Default
dir_path [str

The path to the directory.

required
make_dirs bool

Whether to create the directory if it does not exist. Defaults to True.

True

Raises:

Type Description
FileNotFoundError

If the directory could not be found.

TypeError

If the input directory path is not a string.

Returns:

Type Description
str

The path to the directory.

check_file_path(file_path, make_dirs=True)

Gets the absolute file path.

Parameters:

Name Type Description Default
file_path str

The path to the file.

required
make_dirs bool

Whether to create the directory if it does not exist. Defaults to True.

True

Raises:

Type Description
FileNotFoundError

If the directory could not be found.

TypeError

If the input directory path is not a string.

Returns:

Type Description
str

The absolute path to the file.

check_html_string(html_string)

Check if an HTML string contains local images and convert them to base64.

Parameters:

Name Type Description Default
html_string str

The HTML string.

required

Returns:

Type Description
str

The HTML string with local images converted to base64.

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.

check_titiler_endpoint(titiler_endpoint=None)

Returns the default titiler endpoint.

Returns:

Type Description
Any

The titiler endpoint.

check_url(url)

Check if an HTTP URL is working.

Parameters:

Name Type Description Default
url str

The URL to check.

required

Returns:

Type Description
bool

True if the URL is working (returns a 200 status code), False otherwise.

classify(data, column, cmap=None, colors=None, labels=None, scheme='Quantiles', k=5, legend_kwds=None, classification_kwds=None)

Classify a dataframe column using a variety of classification schemes.

Parameters:

Name Type Description Default
data str | DataFrame | GeoDataFrame

The data to classify. It can be a filepath to a vector dataset, a pandas dataframe, or a geopandas geodataframe.

required
column str

The column to classify.

required
cmap str

The name of a colormap recognized by matplotlib. Defaults to None.

None
colors list

A list of colors to use for the classification. Defaults to None.

None
labels list

A list of labels to use for the legend. Defaults to None.

None
scheme str

Name of a choropleth classification scheme (requires mapclassify). Name of a choropleth classification scheme (requires mapclassify). A mapclassify.MapClassifier object will be used under the hood. Supported are all schemes provided by mapclassify (e.g. 'BoxPlot', 'EqualInterval', 'FisherJenks', 'FisherJenksSampled', 'HeadTailBreaks', 'JenksCaspall', 'JenksCaspallForced', 'JenksCaspallSampled', 'MaxP', 'MaximumBreaks', 'NaturalBreaks', 'Quantiles', 'Percentiles', 'StdMean', 'UserDefined'). Arguments can be passed in classification_kwds.

'Quantiles'
k int

Number of classes (ignored if scheme is None or if column is categorical). Default to 5.

5
legend_kwds dict

Keyword arguments to pass to :func:matplotlib.pyplot.legend or matplotlib.pyplot.colorbar. Defaults to None. Keyword arguments to pass to :func:matplotlib.pyplot.legend or Additional accepted keywords when scheme is specified: fmt : string A formatting specification for the bin edges of the classes in the legend. For example, to have no decimals: {"fmt": "{:.0f}"}. labels : list-like A list of legend labels to override the auto-generated labblels. Needs to have the same number of elements as the number of classes (k). interval : boolean (default False) An option to control brackets from mapclassify legend. If True, open/closed interval brackets are shown in the legend.

None
classification_kwds dict

Keyword arguments to pass to mapclassify. Defaults to None.

None

Returns:

Type Description
Tuple[Any, Dict[str, Any]]

A pandas dataframe with the classification applied and a legend dictionary.

clip_image(image, mask, output, to_cog=True)

Clip an image by mask.

Parameters:

Name Type Description Default
image str

Path to the image file in GeoTIFF format.

required
mask str | list | dict

The mask used to extract the image. It can be a path to vector datasets (e.g., GeoJSON, Shapefile), a list of coordinates, or m.user_roi.

required
output str

Path to the output file.

required
to_cog bool

Flags to indicate if you want to convert the output to COG. Defaults to True.

True

Raises:

Type Description
ImportError

If the fiona or rasterio package is not installed.

FileNotFoundError

If the image is not found.

ValueError

If the mask is not a valid GeoJSON or raster file.

FileNotFoundError

If the mask file is not found.

clip_raster(image, geometry, geom_crs=None, dst_crs=None, resolution=None, driver='COG', compress='DEFLATE', bands=None, match_raster=None, output=None, verbose=True, **kwargs)

Clip a raster by a geometry.

Parameters:

Name Type Description Default
image str

Path to the image file in GeoTIFF format.

required
geometry str | GeoDataFrame | dict | list

The geometry to clip the raster by. It can be a path to vector datasets (e.g., GeoJSON, Shapefile), a geopandas.GeoDataFrame, a dictionary, or a list of 4 numbers (minx, miny, maxx, maxy) representing a bounding box.

required
geom_crs str

The coordinate reference system of the geometry. Defaults to None.

None
dst_crs str

The coordinate reference system of the output raster. Defaults to None.

None
resolution int

The resolution of the output raster. Defaults to None. If a single value is provided, the resolution will be the same in both x and y directions. If a tuple of two values is provided, the first value will be the resolution in the x direction and the second value will be the resolution in the y direction.

None
driver str

The driver of the output raster. Defaults to "COG".

'COG'
compress str

The compression of the output raster. Defaults to "DEFLATE".

'DEFLATE'
bands list

The indices of the bands to clip. Defaults to None. Start from 1.

None
match_raster str

Path to the raster to match the resolution and CRS of the output raster. Defaults to None.

None
output str

Path to the output raster file. Defaults to None.

None
**kwargs Any

Additional keyword arguments to pass to rasterio.reproject.

{}

clip_vector(input_gdf, clip_geom=None, bbox=None, output=None)

Clip a vector dataset using either a bounding box or another vector dataset.

Parameters:

Name Type Description Default
input_gdf str | Path | GeoDataFrame

The input vector data, either as a file path or a GeoDataFrame.

required
clip_geom str | Path | GeoDataFrame

A vector dataset used for clipping, either as a file path or GeoDataFrame.

None
bbox tuple

Bounding box defined as (minx, miny, maxx, maxy).

None
output str | Path

File path to save the clipped result. If None, the result is not saved.

None

Returns:

Type Description
Any

The clipped GeoDataFrame.

Raises:

Type Description
ValueError

If both clip_geom and bbox are provided or neither is provided.

ValueError

If bbox is not a 4-element tuple or list.

close_duckdb_connections(database_path=None, quiet=True)

Close DuckDB connections for a specific database or all databases.

This function closes all connections in the connection pool for the specified database, allowing other programs to access the database file. This is useful when you're done using the database and want to release the file lock.

Parameters:

Name Type Description Default
database_path str

Path to the DuckDB database file. If None, closes connections for all databases. Defaults to None.

None
quiet bool

If True, suppress status messages. Defaults to True.

True

Returns:

Type Description

None

Example

import leafmap

After using add_duckdb_layer

m = leafmap.Map() m.add_duckdb_layer("tiles.db")

Later, close the connections

leafmap.close_duckdb_connections()

Or close connections for a specific database

leafmap.close_duckdb_connections("tiles.db")

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.

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].

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).

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.

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.

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.

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.

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://titiler.opengeos.org".

None

Returns:

Type Description
List

A list of band names.

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://titiler.opengeos.org".

None

Returns:

Name Type Description
list List

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

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://titiler.opengeos.org".

None

Returns:

Type Description
Tuple

A tuple representing (longitude, latitude).

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://titiler.opengeos.org".

None

Returns:

Name Type Description
list List

A dictionary of band info.

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://titiler.opengeos.org".

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.

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://titiler.opengeos.org".

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.

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://titiler.opengeos.org", "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.

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://titiler.opengeos.org".

None

Returns:

Name Type Description
list List

A dictionary of band statistics.

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://titiler.opengeos.org".

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.

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://titiler.opengeos.org".

None
percentile bool

Whether to use percentiles or not. Defaults to True.

True

cog_validate(source, verbose=False)

Validate Cloud Optimized Geotiff.

Parameters:

Name Type Description Default
source str

A dataset path or URL. Will be opened in "r" mode.

required
verbose bool

Whether to print the output of the validation. Defaults to False.

False

Raises:

Type Description
ImportError

If the rio-cogeo package is not installed.

FileNotFoundError

If the provided file could not be found.

Returns:

Type Description
Tuple[bool, List[str], List[str]]

A tuple containing the validation results (True if src_path is a valid COG, list of validation errors, and a list of validation warnings).

color_code_dataframe(data, legend_dict)

Converts values in a dataframe to color codes based on a legend dictionary.

This function takes a dataframe (or path to a dataframe) and a legend dictionary and returns a new dataframe with values replaced by their corresponding color codes. It supports both numeric range legends and categorical legends.

Parameters:

Name Type Description Default
data Union[str, DataFrame, GeoDataFrame]

Input data source, can be: - Path to a CSV file or geospatial file - pandas DataFrame - geopandas GeoDataFrame

required
legend_dict Dict[str, str]

Dictionary mapping values to colors, can be: - Numeric ranges ("[ 100000, 200000]") mapped to color codes - Categorical values ("low", "medium") mapped to color codes - Can include a "Nodata" key for None/NaN values

required

Returns:

Type Description
Union[DataFrame, GeoDataFrame]

A new dataframe with values replaced by color codes, preserving the

Union[DataFrame, GeoDataFrame]

input data type (DataFrame or GeoDataFrame)

Raises:

Type Description
TypeError

If the input data type is not supported

ValueError

If the file format is not supported

Examples:

1
2
3
4
5
6
7
>>> # Example with numeric ranges
>>> range_legend = {
...     "[ 0, 200000]": "#daeaf6",
...     "(200001, 400000]": "#9ecae1",
...     "Nodata": "#f0f0f0"
... }
>>> color_df = color_code_dataframe("housing_data.csv", range_legend)
1
2
3
4
5
6
7
8
9
>>> # Example with categorical values
>>> cat_legend = {
...     "low": "#daeaf6",
...     "medium": "#9ecae1",
...     "high": "#2171b5",
...     "Nodata": "#f0f0f0"
... }
>>> df = pd.DataFrame({"Risk": ["low", "medium", "high", None]})
>>> color_df = color_code_dataframe(df, cat_legend)

configure_jupyterhub(base_url=None)

Auto-configure leafmap for JupyterHub environments.

This function automatically detects if running in a JupyterHub environment and configures the necessary environment variables for tile server proxying. It will be called automatically by add_duckdb_layer, so you typically don't need to call it manually.

Parameters:

Name Type Description Default
base_url str

The base URL of your JupyterHub instance (e.g., "https://jupyter.example.com"). Required for MapLibre vector tiles due to URL validation requirements. If not provided, vector tiles may not work.

None
Example

import leafmap

Specify your JupyterHub URL for vector tile support

leafmap.configure_jupyterhub("https://your-jupyterhub-domain.com")

Now add_duckdb_layer will work correctly

Note

MapLibre GL JS's vector tile sources require absolute URLs (with http:// or https://). Raster tiles (add_raster) work with relative URLs, but vector tiles (add_duckdb_layer) do not. This is a limitation of MapLibre GL JS, not leafmap.

connect_points_as_line(gdf, sort_column=None, crs='EPSG:4326', single_line=True)

Connects points in a GeoDataFrame into either a single LineString or multiple LineStrings based on a specified sort column or the index if no column is provided. The resulting GeoDataFrame will have the specified CRS.

Parameters:

Name Type Description Default
gdf GeoDataFrame

A GeoDataFrame containing point geometries.

required
sort_column Optional[str]

Column name to sort the points by (e.g., 'timestamp'). If None, the index is used for sorting. Defaults to None.

None
crs str

The coordinate reference system (CRS) for the resulting GeoDataFrame. Defaults to "EPSG:4326".

'EPSG:4326'
single_line bool

If True, generates a single LineString connecting all points. If False, generates multiple LineStrings, each connecting two consecutive points. Defaults to True.

True

Returns:

Type Description
GeoDataFrame

A new GeoDataFrame containing either a single LineString or multiple LineString geometries. based on the single_line parameter, with the specified CRS.

Example

line_gdf = connect_points_as_line(gdf, 'timestamp', crs="EPSG:3857", single_line=True) line_gdf = connect_points_as_line(gdf, single_line=False) # Uses index and defaults to EPSG:4326

connect_postgis(database, host='localhost', user=None, password=None, port=5432, use_env_var=False)

Connects to a PostGIS database.

Parameters:

Name Type Description Default
database str

Name of the database

required
host str

Hosting server for the database. Defaults to "localhost".

'localhost'
user str

User name to access the database. Defaults to None.

None
password str

Password to access the database. Defaults to None.

None
port int

Port number to connect to at the server host. Defaults to 5432.

5432
use_env_var bool

Whether to use environment variables. It set to True, user and password are treated as an environment variables with default values user="SQL_USER" and password="SQL_PASSWORD". Defaults to False.

False

Raises:

Type Description
ValueError

If user is not specified.

ValueError

If password is not specified.

Returns:

Type Description
Any

A SQLAlchemy engine connection string or engine object.

construct_bbox(*args, buffer=0.001, crs='EPSG:4326', return_gdf=False)

Construct a bounding box (bbox) geometry based on either a centroid point or bbox.

Parameters:

Name Type Description Default
*args Union[float, Tuple[float, float, float, float]]

Coordinates for the geometry. - If 2 arguments are provided, it is interpreted as a centroid (x, y) with a buffer. - If 4 arguments are provided, it is interpreted as a bbox (minx, miny, maxx, maxy).

()
buffer float

The buffer distance around the centroid point (default is 0.01 degrees).

0.001
crs str

The coordinate reference system (default is "EPSG:4326").

'EPSG:4326'
return_gdf bool

Whether to return a GeoDataFrame (default is False).

False

Returns:

Type Description
Union[Polygon, GeoDataFrame]

The constructed bounding box (Polygon).

convert_coordinates(x, y, source_crs, target_crs='epsg:4326')

Convert coordinates from the source EPSG code to the target EPSG code.

Parameters:

Name Type Description Default
x float

The x-coordinate of the point.

required
y float

The y-coordinate of the point.

required
source_crs str

The EPSG code of the source coordinate system.

required
target_crs str

The EPSG code of the target coordinate system. Defaults to '4326' (EPSG code for WGS84).

'epsg:4326'

Returns:

Type Description
Tuple[float, float]

A tuple containing the converted longitude and latitude.

convert_lidar(source, destination=None, point_format_id=None, file_version=None, **kwargs)

Converts a Las from one point format to another Automatically upgrades the file version if source file version is not compatible with the new point_format_id

Parameters:

Name Type Description Default
source str | LasBase

The source data to be converted.

required
destination str

The destination file path. Defaults to None.

None
point_format_id int

The new point format id (the default is None, which won't change the source format id).

None
file_version str

The new file version. None by default which means that the file_version may be upgraded for compatibility with the new point_format. The file version will not be downgraded.

None

Returns:

Type Description
Any

The converted LasData object.

convert_to_cog(images, output_dir, prefix='', suffix='_cog', extra_options=None)

Convert all .tif files in a directory to Cloud Optimized GeoTIFFs (COGs).

Parameters:

Name Type Description Default
images str | list

Input directory containing .tif files, or a list of .tif file paths.

required
output_dir str

Path to the output directory where COGs will be saved.

required
prefix str

Prefix to add to the output filenames.

''
suffix str

Suffix to add to the output filenames before the .tif extension.

'_cog'
extra_options List[str]

Additional gdal_translate options. Example: ["-co", "TILED=YES", "-co", "BLOCKSIZE=512"]

None

convert_to_gdf(data, geometry=None, lat=None, lon=None, crs='EPSG:4326', included=None, excluded=None, obj_to_str=False, open_args=None, **kwargs)

Convert data to a GeoDataFrame.

Parameters:

Name Type Description Default
data Union[DataFrame, str]

The input data, either as a DataFrame or a file path.

required
geometry Optional[str]

The column name containing geometry data. Defaults to None.

None
lat Optional[str]

The column name containing latitude data. Defaults to None.

None
lon Optional[str]

The column name containing longitude data. Defaults to None.

None
crs str

The coordinate reference system to use. Defaults to "EPSG:4326".

'EPSG:4326'
included Optional[List[str]]

List of columns to include. Defaults to None.

None
excluded Optional[List[str]]

List of columns to exclude. Defaults to None.

None
obj_to_str bool

Whether to convert object dtype columns to string. Defaults to False.

False
open_args Optional[Dict[str, Any]]

Additional arguments for file opening functions. Defaults to None.

None
**kwargs Any

Additional keyword arguments for GeoDataFrame creation.

{}

Returns:

Type Description
GeoDataFrame

The converted GeoDataFrame.

Raises:

Type Description
ValueError

If the file format is unsupported or required columns are not provided.

coords_to_geojson(coords)

Convert a list of bbox coordinates representing [left, bottom, right, top] to geojson FeatureCollection.

Parameters:

Name Type Description Default
coords list

A list of bbox coordinates representing [left, bottom, right, top].

required

Returns:

Type Description
Dict[str, Any]

A geojson FeatureCollection.

coords_to_vector(coords, output=None, crs='EPSG:4326', **kwargs)

Convert a list of coordinates to a GeoDataFrame or a vector file.

Parameters:

Name Type Description Default
coords list

A list of coordinates in the format of [(x1, y1), (x2, y2), ...].

required
output str

The path to the output vector file. Defaults to None.

None
crs str

The CRS of the coordinates. Defaults to "EPSG:4326".

'EPSG:4326'

Returns:

Type Description
Any

A GeoDataFrame of the coordinates.

coords_to_xy(src_fp, coords, coord_crs='epsg:4326', request_payer='bucket-owner', env_args={}, open_args={}, **kwargs)

Converts a list of coordinates to pixel coordinates, i.e., (col, row) coordinates.

Parameters:

Name Type Description Default
src_fp str

The source raster file path.

required
coords list

A list of coordinates in the format of [[x1, y1], [x2, y2], ...]

required
coord_crs str

The coordinate CRS of the input coordinates. Defaults to "epsg:4326".

'epsg:4326'
request_payer str

Specifies who pays for the download from S3. Can be "bucket-owner" or "requester". Defaults to "bucket-owner".

'bucket-owner'
env_args dict

Additional keyword arguments to pass to rasterio.Env.

{}
open_args dict

Additional keyword arguments to pass to rasterio.open.

{}
**kwargs Any

Additional keyword arguments to pass to rasterio.transform.rowcol.

{}

Returns:

Type Description
list

A list of pixel coordinates in the format of [[x1, y1], [x2, y2], ...]

create_code_cell(code='', where='below')

Creates a code cell in the IPython Notebook.

Parameters:

Name Type Description Default
code str

Code to fill the new code cell with. Defaults to ''.

''
where str

Where to add the new code cell. It can be one of the following: above, below, at_bottom. Defaults to 'below'.

'below'

Downloads a file from voila. Adopted from https://github.com/voila-dashboards/voila/issues/578

Parameters:

Name Type Description Default
filename str

The file path to the file to download

required
title str

str. Defaults to "Click here to download: ".

'Click here to download: '

Returns:

Type Description
Any

HTML download URL.

create_legend(title='Legend', labels=None, colors=None, legend_dict=None, builtin_legend=None, opacity=1.0, position='bottomright', draggable=True, output=None, style={}, shape_type='rectangle')

Create a legend in HTML format. Reference: https://bit.ly/3oV6vnH

Parameters:

Name Type Description Default
title str

Title of the legend. Defaults to 'Legend'. Defaults to "Legend".

'Legend'
colors list

A list of legend colors. Defaults to None.

None
labels list

A list of legend labels. Defaults to None.

None
legend_dict dict

A dictionary containing legend items as keys and color as values. If provided, legend_keys and legend_colors will be ignored. Defaults to None.

None
builtin_legend str

Name of the builtin legend to add to the map. Defaults to None.

None
opacity float

The opacity of the legend. Defaults to 1.0.

1.0
position str

The position of the legend, can be one of the following: "topleft", "topright", "bottomleft", "bottomright". Defaults to "bottomright".

'bottomright'
draggable bool

If True, the legend can be dragged to a new position. Defaults to True.

True
output str

The output file path (*.html) to save the legend. Defaults to None.

None
style dict

Additional keyword arguments to style the legend, such as position, bottom, right, z-index, border, background-color, border-radius, padding, font-size, etc. The default style is: style = { 'position': 'fixed', 'z-index': '9999', 'border': '2px solid grey', 'background-color': 'rgba(255, 255, 255, 0.8)', 'border-radius': '5px', 'padding': '10px', 'font-size': '14px', 'bottom': '20px', 'right': '5px' }

{}

Returns:

Type Description
str

The HTML code of the legend.

create_lines_from_points(src_points, dst_points, col='id', distance_col='distance', decimal_places=2, return_gdf=False)

Create LineString features between matching point features from two GeoJSON FeatureCollections based on a shared column (default is 'id').

Parameters:

Name Type Description Default
src_points Union[dict, str, GeoDataFrame]

Source GeoJSON FeatureCollection with point features.

required
dst_points Union[dict, str, GeoDataFrame]

Destination GeoJSON FeatureCollection with point features.

required
col str

The property name to match features between the two collections.

'id'
distance_col str

The name of the column to store the distance between the points.

'distance'
decimal_places int

The number of decimal places to round the distance to.

2
return_gdf bool

If True, returns a GeoDataFrame instead of a dictionary. Defaults to False.

False

Returns:

Type Description
dict

A GeoJSON FeatureCollection containing LineString features.

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

create_timelapse(images, out_gif, ext='.tif', bands=None, size=None, bbox=None, fps=5, loop=0, add_progress_bar=True, progress_bar_color='blue', progress_bar_height=5, add_text=False, text_xy=None, text_sequence=None, font_type='arial.ttf', font_size=20, font_color='black', mp4=False, quiet=True, reduce_size=False, clean_up=True, **kwargs)

Creates a timelapse gif from a list of images.

Parameters:

Name Type Description Default
images list | str

The list of images or input directory to create the gif from. For example, '/path/to/images/*.tif' or ['/path/to/image1.tif', '/path/to/image2.tif', ...]

required
out_gif str

File path to the output gif.

required
ext str

The extension of the images. Defaults to '.tif'.

'.tif'
bands list

The bands to use for the gif. For example, [0, 1, 2] for RGB, and [0] for grayscale. Defaults to None.

None
size tuple

The size of the gif. For example, (500, 500). Defaults to None, using the original size.

None
bbox list

The bounding box of the gif. For example, [xmin, ymin, xmax, ymax]. Defaults to None, using the original bounding box.

None
fps int

The frames per second of the gif. Defaults to 5.

5
loop int

The number of times to loop the gif. Defaults to 0, looping forever.

0
add_progress_bar bool

Whether to add a progress bar to the gif. Defaults to True.

True
progress_bar_color str

The color of the progress bar, can be color name or hex code. Defaults to 'blue'.

'blue'
progress_bar_height int

The height of the progress bar. Defaults to 5.

5
add_text bool

Whether to add text to the gif. Defaults to False.

False
text_xy tuple

The x, y coordinates of the text. For example, ('10%', '10%'). Defaults to None, using the bottom left corner.

None
text_sequence list

The sequence of text to add to the gif. For example, ['year 1', 'year 2', ...].

None
font_type str

The font type of the text, can be 'arial.ttf' or 'alibaba.otf', or any system font. Defaults to 'arial.ttf'.

'arial.ttf'
font_size int

The font size of the text. Defaults to 20.

20
font_color str

The color of the text, can be color name or hex code. Defaults to 'black'.

'black'
mp4 bool

Whether to convert the gif to mp4. Defaults to False.

False
quiet bool

Whether to print the progress. Defaults to False.

True
reduce_size bool

Whether to reduce the size of the gif using ffmpeg. Defaults to False.

False
clean_up bool

Whether to clean up the temporary files. Defaults to True.

True

csv_points_to_shp(in_csv, out_shp, latitude='latitude', longitude='longitude')

Converts a csv file containing points (latitude, longitude) into a shapefile.

Parameters:

Name Type Description Default
in_csv str

File path or HTTP URL to the input csv file. For example, https://raw.githubusercontent.com/opengeos/data/main/world/world_cities.csv

required
out_shp str

File path to the output shapefile.

required
latitude str

Column name for the latitude column. Defaults to 'latitude'.

'latitude'
longitude str

Column name for the longitude column. Defaults to 'longitude'.

'longitude'

csv_to_df(in_csv, **kwargs)

Converts a CSV file to pandas dataframe.

Parameters:

Name Type Description Default
in_csv str

File path to the input CSV.

required

Returns:

Type Description
DataFrame

A pandas DataFrame.

csv_to_gdf(in_csv, latitude='latitude', longitude='longitude', geometry=None, crs='EPSG:4326', encoding='utf-8', **kwargs)

Creates points for a CSV file and converts them to a GeoDataFrame.

Parameters:

Name Type Description Default
in_csv str

The file path to the input CSV file.

required
latitude str

The name of the column containing latitude coordinates. Defaults to "latitude".

'latitude'
longitude str

The name of the column containing longitude coordinates. Defaults to "longitude".

'longitude'
geometry str

The name of the column containing geometry. Defaults to None.

None
crs str

The coordinate reference system. Defaults to "EPSG:4326".

'EPSG:4326'
encoding str

The encoding of characters. Defaults to "utf-8".

'utf-8'

Returns:

Type Description
GeoDataFrame

A GeoDataFrame.

csv_to_geojson(in_csv, out_geojson=None, latitude='latitude', longitude='longitude', encoding='utf-8')

Creates points for a CSV file and exports data as a GeoJSON.

Parameters:

Name Type Description Default
in_csv str

The file path to the input CSV file.

required
out_geojson str

The file path to the exported GeoJSON. Default to None.

None
latitude str

The name of the column containing latitude coordinates. Defaults to "latitude".

'latitude'
longitude str

The name of the column containing longitude coordinates. Defaults to "longitude".

'longitude'
encoding str

The encoding of characters. Defaults to "utf-8".

'utf-8'

csv_to_shp(in_csv, out_shp, latitude='latitude', longitude='longitude', encoding='utf-8')

Converts a csv file with latlon info to a point shapefile.

Parameters:

Name Type Description Default
in_csv str

The input csv file containing longitude and latitude columns.

required
out_shp str

The file path to the output shapefile.

required
latitude str

The column name of the latitude column. Defaults to 'latitude'.

'latitude'
longitude str

The column name of the longitude column. Defaults to 'longitude'.

'longitude'

csv_to_vector(in_csv, output, latitude='latitude', longitude='longitude', geometry=None, crs='EPSG:4326', encoding='utf-8', **kwargs)

Creates points for a CSV file and converts them to a vector dataset.

Parameters:

Name Type Description Default
in_csv str

The file path to the input CSV file.

required
output str

The file path to the output vector dataset.

required
latitude str

The name of the column containing latitude coordinates. Defaults to "latitude".

'latitude'
longitude str

The name of the column containing longitude coordinates. Defaults to "longitude".

'longitude'
geometry str

The name of the column containing geometry. Defaults to None.

None
crs str

The coordinate reference system. Defaults to "EPSG:4326".

'EPSG:4326'
encoding str

The encoding of characters. Defaults to "utf-8".

'utf-8'
**kwargs Any

Additional keyword arguments to pass to gdf.to_file().

{}

d2s_tile(url, titiler_endpoint=None, **kwargs)

Generate a D2S tile URL with optional API key.

Parameters:

Name Type Description Default
url str

The base URL for the tile.

required
titiler_endpoint str

The endpoint for the titiler service. Defaults to "https://tt.d2s.org".

None
**kwargs Any

Additional keyword arguments to pass to the cog_stats function.

{}

Returns:

Type Description
str

The modified URL with the API key if required, otherwise the original URL.

Raises:

Type Description
ValueError

If the API key is required but not set in the environment variables.

delete_shp(in_shp, verbose=False)

Deletes a shapefile.

Parameters:

Name Type Description Default
in_shp str

The input shapefile to delete.

required
verbose bool

Whether to print out descriptive text. Defaults to True.

False

df_to_gdf(df, geometry='geometry', src_crs='EPSG:4326', dst_crs=None, **kwargs)

Converts a pandas DataFrame to a GeoPandas GeoDataFrame.

Parameters:

Name Type Description Default
df DataFrame

The pandas DataFrame to convert.

required
geometry str

The name of the geometry column in the DataFrame.

'geometry'
src_crs str

The coordinate reference system (CRS) of the GeoDataFrame. Default is "EPSG:4326".

'EPSG:4326'
dst_crs str

The target CRS of the GeoDataFrame. Default is None

None

Returns:

Type Description
Any

The converted GeoPandas GeoDataFrame.

df_to_geojson(df, out_geojson=None, latitude='latitude', longitude='longitude', encoding='utf-8')

Creates points for a Pandas DataFrame and exports data as a GeoJSON.

Parameters:

Name Type Description Default
df DataFrame

The input Pandas DataFrame.

required
out_geojson str

The file path to the exported GeoJSON. Default to None.

None
latitude str

The name of the column containing latitude coordinates. Defaults to "latitude".

'latitude'
longitude str

The name of the column containing longitude coordinates. Defaults to "longitude".

'longitude'
encoding str

The encoding of characters. Defaults to "utf-8".

'utf-8'

dict_to_json(data, file_path, indent=4)

Writes a dictionary to a JSON file.

Parameters:

Name Type Description Default
data dict

A dictionary.

required
file_path str

The path to the JSON file.

required
indent int

The indentation of the JSON file. Defaults to 4.

4

Raises:

Type Description
TypeError

If the input data is not a dictionary.

disjoint(input_features, selecting_features, output=None, **kwargs)

Find the features in the input_features that do not intersect the selecting_features.

Parameters:

Name Type Description Default
input_features str | GeoDataFrame

The input features to select from. Can be a file path or a GeoDataFrame.

required
selecting_features str | GeoDataFrame

The features in the Input Features parameter will be selected based on their relationship to the features from this layer.

required
output are

The output path to save the GeoDataFrame in a vector format (e.g., shapefile). Defaults to None.

None

Returns:

Type Description
Any

The path to the output file or the GeoDataFrame.

display_html(html, width='100%', height=500)

Displays an HTML file or HTML string in a Jupyter Notebook.

Parameters:

Name Type Description Default
html Union[str, bytes]

Path to an HTML file or an HTML string.

required
width str

Width of the displayed iframe. Default is '100%'.

'100%'
height int

Height of the displayed iframe. Default is 500.

500

Returns:

Type Description
None

None

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.

download_file(url=None, output=None, quiet=False, proxy=None, speed=None, use_cookies=True, verify=True, id=None, fuzzy=False, resume=False, unzip=True, overwrite=False, subfolder=False)

Download a file from URL, including Google Drive shared URL.

Parameters:

Name Type Description Default
url str

Google Drive URL is also supported. Defaults to None.

None
output str

Output filename. Default is basename of URL.

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
unzip bool

Unzip the file. Defaults to True.

True
overwrite bool

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

False
subfolder bool

Create a subfolder with the same name as the file. Defaults to False.

False

Returns:

Type Description
str

The output file path.

download_file_lite(url, output=None, binary=False, overwrite=False, **kwargs) async

Download a file using Pyodide. This function is only available on JupyterLite. Call the function with await, such as await download_file_lite(url).

Parameters:

Name Type Description Default
url str

The URL of the file.

required
output str

The local path to save the file. Defaults to None.

None
binary bool

Whether the file is binary. Defaults to False.

False
overwrite bool

Whether to overwrite the file if it exists. Defaults to False.

False

download_files(urls, out_dir=None, filenames=None, quiet=False, proxy=None, speed=None, use_cookies=True, verify=True, id=None, fuzzy=False, resume=False, unzip=True, overwrite=False, subfolder=False, multi_part=False)

Download files from URLs, including Google Drive shared URL.

Parameters:

Name Type Description Default
urls list

The list of urls to download. Google Drive URL is also supported.

required
out_dir str

The output directory. Defaults to None.

None
filenames list

Output filename. Default is basename of URL.

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
unzip bool

Unzip the file. Defaults to True.

True
overwrite bool

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

False
subfolder bool

Create a subfolder with the same name as the file. Defaults to False.

False
multi_part bool

If the file is a multi-part file. Defaults to False.

False
1
2
3
4
files = ["sam_hq_vit_tiny.zip", "sam_hq_vit_tiny.z01", "sam_hq_vit_tiny.z02", "sam_hq_vit_tiny.z03"]
base_url = "https://github.com/opengeos/datasets/releases/download/models/"
urls = [base_url + f for f in files]
leafmap.download_files(urls, out_dir="models", multi_part=True)

download_folder(url=None, id=None, output=None, quiet=False, proxy=None, speed=None, use_cookies=True, remaining_ok=False)

Downloads the entire folder from URL.

Parameters:

Name Type Description Default
url str

URL of the Google Drive folder. Must be of the format 'https://drive.google.com/drive/folders/{url}'. Defaults to None.

None
id str

Google Drive's folder ID. Defaults to None.

None
output str

String containing the path of the output folder. Defaults to current working directory.

None
quiet bool

Suppress terminal output. Defaults to 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

Returns:

Type Description
Optional[List[str]]

List of files downloaded, or None if failed.

download_from_url(url, out_file_name=None, out_dir='.', unzip=True, verbose=True)

Download a file from a URL (e.g., https://github.com/opengeos/whitebox-python/raw/master/examples/testdata.zip)

Parameters:

Name Type Description Default
url str

The HTTP URL to download.

required
out_file_name str

The output file name to use. Defaults to None.

None
out_dir str

The output directory to use. Defaults to '.'.

'.'
unzip bool

Whether to unzip the downloaded file if it is a zip file. Defaults to True.

True
verbose bool

Whether to display or not the output of the function

True

download_google_buildings(location, out_dir=None, merge_output=None, head=None, keep_geojson=False, overwrite=False, quiet=False, **kwargs)

Download Google Open Building dataset for a specific location. Check the dataset links from https://sites.research.google/open-buildings.

Parameters:

Name Type Description Default
location str

The location name for which to download the dataset.

required
out_dir Optional[str]

The output directory to save the downloaded files. If not provided, the current working directory is used.

None
merge_output Optional[str]

Optional. The output file path for merging the downloaded files into a single GeoDataFrame.

None
head Optional[int]

Optional. The number of files to download. If not provided, all files will be downloaded.

None
keep_geojson bool

Optional. If True, the GeoJSON files will be kept after converting them to CSV files.

False
overwrite bool

Optional. If True, overwrite the existing files.

False
quiet bool

Optional. If True, suppresses the download progress messages.

False
**kwargs Any

Additional keyword arguments to be passed to the gpd.to_file function.

{}

Returns:

Type Description
List[str]

A list of file paths of the downloaded files.

download_mapillary_image(image_id, output=None, resolution='original', access_token=None, quiet=True, **kwargs)

Downloads a Mapillary image.

Parameters:

Name Type Description Default
image_id str

The ID of the Mapillary image.

required
output str

The output file path. Defaults to None.

None
resolution str

The resolution of the image. Can be 256, 1024, 2048, or original. Defaults to "original".

'original'
access_token str

The access token for the Mapillary API. Defaults to None.

None
quiet bool

Whether to suppress output. Defaults to True.

True
**kwargs Any

Additional keyword arguments for the download.

{}

Returns:

Type Description
None

None

download_mapillary_images(image_ids, output_dir=None, resolution='original', **kwargs)

Downloads multiple Mapillary images.

Parameters:

Name Type Description Default
image_ids List[str]

A list of Mapillary image IDs.

required
output_dir str

The directory to save the images. Defaults to the current working directory.

None
resolution str

The resolution of the images. Defaults to "original".

'original'
**kwargs Any

Additional keyword arguments for the download.

{}

Returns:

Type Description
None

None

download_ms_buildings(location, out_dir=None, merge_output=None, head=None, quiet=False, **kwargs)

Download Microsoft Buildings dataset for a specific location. Check the dataset links from https://minedbuildings.blob.core.windows.net/global-buildings/dataset-links.csv.

Parameters:

Name Type Description Default
location str

The location name for which to download the dataset.

required
out_dir str

The output directory to save the downloaded files. If not provided, the current working directory is used.

None
merge_output str

The output file path for merging the downloaded files into a single GeoDataFrame.

None
head int

The number of files to download. If not provided, all files will be downloaded.

None
quiet bool

If True, suppresses the download progress messages.

False
**kwargs Any

Additional keyword arguments to be passed to the gpd.to_file function.

{}

Returns:

Type Description
List[str]

A list of file paths of the downloaded files.

download_ned(region, out_dir=None, return_url=False, download_args={}, geopandas_args={}, query={})

Download the US National Elevation Datasets (NED) for a region.

Parameters:

Name Type Description Default
region str | list

A filepath to a vector dataset or a list of bounds in the form of [minx, miny, maxx, maxy].

required
out_dir str

The directory to download the files to. Defaults to None, which uses the current working directory.

None
return_url bool

Whether to return the download URLs of the files. Defaults to False.

False
download_args dict

A dictionary of arguments to pass to the download_file function. Defaults to {}.

{}
geopandas_args dict

A dictionary of arguments to pass to the geopandas.read_file() function. Used for reading a region URL|filepath.

{}
query dict

A dictionary of arguments to pass to the The_national_map_USGS.find_details() function. See https://apps.nationalmap.gov/tnmaccess/#/product for more information.

{}

Returns:

Type Description
Union[None, List]

A list of the download URLs of the files if return_url is True.

download_nlcd(years, out_dir=None, quiet=False, **kwargs)

Downloads NLCD (National Land Cover Database) files for the specified years.

Parameters:

Name Type Description Default
years List[int]

A list of years for which to download the NLCD files.

required
out_dir str

The directory where the downloaded files will be saved. Defaults to the current working directory.

None
quiet bool

If True, suppresses download progress messages. Defaults to False.

False
**kwargs Any

Additional keyword arguments to pass to the download_file function.

{}

Returns:

Type Description
None

None

download_osm(m)

Widget for downloading OSM data.

Parameters:

Name Type Description Default
m Map

The leaflet Map object. Defaults to None.

required

Returns:

Name Type Description
ipywidgets

The tool GUI widget.

download_tnm(region=None, out_dir=None, return_url=False, download_args={}, geopandas_args={}, API={})

Download the US National Elevation Datasets (NED) for a region.

Parameters:

Name Type Description Default
region str | list

An URL|filepath to a vector dataset Or a list of bounds in the form of [minx, miny, maxx, maxy]. Alternatively you could use API parameters such as polygon or bbox.

None
out_dir str

The directory to download the files to. Defaults to None, which uses the current working directory.

None
return_url bool

Whether to return the download URLs of the files. Defaults to False.

False
download_args dict

A dictionary of arguments to pass to the download_file function. Defaults to {}.

{}
geopandas_args dict

A dictionary of arguments to pass to the geopandas.read_file() function. Used for reading a region URL|filepath.

{}
API dict

A dictionary of arguments to pass to the The_national_map_USGS.find_details() function. Exposes most of the documented API. Defaults to {}

{}

Returns:

Type Description
Union[None, List]

A list of the download URLs of the files if return_url is True.

edit_download_html(htmlWidget, filename, title='Click here to download: ')

Downloads a file from voila. Adopted from https://github.com/voila-dashboards/voila/issues/578#issuecomment-617668058

Parameters:

Name Type Description Default
htmlWidget object

The HTML widget to display the URL.

required
filename str

File path to download.

required
title str

Download description. Defaults to "Click here to download: ".

'Click here to download: '

edit_draw_gui(m)

Generates a tool GUI for editing vector data attribute table.

Parameters:

Name Type Description Default
m Map

The leaflet Map object. Defaults to None.

required

Returns:

Name Type Description
ipywidgets

The tool GUI widget.

ee_initialize(key_data=None, token_name='EE_SERVICE_ACCOUNT')

Initialize the Earth Engine API.

Parameters:

Name Type Description Default
key_data Optional[str]

The key data to use for authentication. Must be a JSON string containing service account credentials, with at least a 'client_email' field (e.g., the contents of a Google service account key file).

None
token_name str

The name of the environment variable to use for authentication.

'EE_SERVICE_ACCOUNT'

ee_tile_url(ee_object=None, vis_params={}, asset_id=None, ee_initialize=False, project_id=None, **kwargs)

Adds a Google Earth Engine tile layer to the map based on the tile layer URL from https://github.com/opengeos/ee-tile-layers/blob/main/datasets.tsv.

Parameters:

Name Type Description Default
ee_object object

The Earth Engine object to display.

None
vis_params dict

Visualization parameters. For example, {'min': 0, 'max': 100}.

{}
asset_id str

The ID of the Earth Engine asset.

None
ee_initialize bool

Whether to initialize the Earth Engine

False

Returns:

Type Description
None

None

evaluate_model(df, y_col='y', y_pred_col='y_pred', metrics=None, drop_na=True, filter_nonzero=True)

Evaluates the model performance on the given dataframe with customizable options.

Parameters:

Name Type Description Default
df DataFrame

A pandas DataFrame with columns for actual and predicted values.

required
y_col str

Column name for the actual values.

'y'
y_pred_col str

Column name for the predicted values.

'y_pred'
metrics list

A list of metrics to calculate. Available options: - 'r2': R-squared - 'r': Pearson correlation coefficient - 'rmse': Root Mean Squared Error - 'mae': Mean Absolute Error - 'mape': Mean Absolute Percentage Error Defaults to all metrics if None.

None
drop_na bool

Whether to drop rows with NaN in the actual values column.

True
filter_nonzero bool

Whether to filter out rows where actual values are zero.

True

Returns:

Type Description
dict

A dictionary of the selected performance metrics.

execute_maplibre_notebook_dir(in_dir, out_dir, delete_html=True, replace_api_key=True, recursive=False, keep_notebook=False, index_html=True, ignore_files=None)

Executes Jupyter notebooks found in a specified directory, optionally replacing API keys and deleting HTML outputs.

Parameters:

Name Type Description Default
in_dir str

The input directory containing Jupyter notebooks to be executed.

required
out_dir str

The output directory where the executed notebooks and their HTML outputs will be saved.

required
delete_html bool

If True, deletes any existing HTML files in the output directory before execution. Defaults to True.

True
replace_api_key bool

If True, replaces the API key in the output HTML. Defaults to True. set "MAPTILER_KEY" and "MAPTILER_KEY_PUBLIC" to your MapTiler API key and public key, respectively.

True
recursive bool

If True, searches for notebooks in the input directory recursively. Defaults to False.

False
keep_notebook bool

If True, keeps the executed notebooks in the output directory. Defaults to False.

False
index_html bool

If True, generates an index.html file in the output directory listing all files. Defaults to True.

True
ignore_files list

A list of notebook files to ignore during execution. Defaults to None.

None

Returns:

Type Description
None

None

execute_notebook(in_file)

Executes a Jupyter notebook and save output cells

Parameters:

Name Type Description Default
in_file str

Input Jupyter notebook.

required

execute_notebook_dir(in_dir)

Executes all Jupyter notebooks in the given directory recursively and save output cells.

Parameters:

Name Type Description Default
in_dir str

Input folder containing notebooks.

required

explode(coords)

Explode a GeoJSON geometry's coordinates object and yield coordinate tuples. As long as the input is conforming, the type of the geometry doesn't matter. From Fiona 1.4.8

Parameters:

Name Type Description Default
coords list

A list of coordinates.

required

Yields:

Type Description
Any

Coordinate tuples extracted from the input.

extract_archive(archive, outdir=None, **kwargs)

Extracts a multipart archive.

This function uses the patoolib library to extract a multipart archive. If the patoolib library is not installed, it attempts to install it. If the archive does not end with ".zip", it appends ".zip" to the archive name. If the extraction fails (for example, if the files already exist), it skips the extraction.

Parameters:

Name Type Description Default
archive str

The path to the archive file.

required
outdir str

The directory where the archive should be extracted.

None
**kwargs Any

Arbitrary keyword arguments for the patoolib.extract_archive function.

{}

Returns:

Type Description
None

None

Raises:

Type Description
Exception

An exception is raised if the extraction fails for reasons other than the files already existing.

1
2
3
4
files = ["sam_hq_vit_tiny.zip", "sam_hq_vit_tiny.z01", "sam_hq_vit_tiny.z02", "sam_hq_vit_tiny.z03"]
base_url = "https://github.com/opengeos/datasets/releases/download/models/"
urls = [base_url + f for f in files]
leafmap.download_files(urls, out_dir="models", multi_part=True)

extract_parquet_by_bbox(input_parquet, bbox, output_file, geometry='geometry', driver='PARQUET')

Extract buildings that intersect with a specific bounding box in San Diego.

Uses DuckDB with spatial extension to query buildings that intersect with a bounding box and saves the results to a Parquet file.

Parameters:

Name Type Description Default
input_parquet str

Path to the input Parquet file.

required
bbox tuple | list

Bounding box as (minx, miny, maxx, maxy).

required
output_file str

Output file path for resulting Parquet/GeoParquet file.

required
geometry str

Geometry column name. Defaults to "geometry".

'geometry'
driver str

Output driver, e.g., "PARQUET". Defaults to "PARQUET".

'PARQUET'

Returns:

Type Description
None

The function writes the results to the output file.

filter_bounds(data, bbox, within=False, align=True, **kwargs)

Filters a GeoDataFrame or GeoSeries by a bounding box.

Parameters:

Name Type Description Default
data str | GeoDataFrame

The input data to filter. Can be a file path or a GeoDataFrame.

required
bbox list | GeoDataFrame

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

required
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
Any

The filtered data.

filter_date(data, start_date=None, end_date=None, date_field='date', date_args={}, **kwargs)

Filters a DataFrame, GeoDataFrame or GeoSeries by a date range.

Parameters:

Name Type Description Default
data str | DataFrame | GeoDataFrame

The input data to filter. Can be a file path or a DataFrame or GeoDataFrame.

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
date_field str

The name of the date field. Defaults to "date".

'date'
date_args dict

Additional arguments for pd.to_datetime. Defaults to {}.

{}

Returns:

Type Description
Any

The filtered data.

filter_geom_type(data, geom_type, output=None, **kwargs)

Filters a GeoDataFrame based on the geometry type.

Parameters:

Name Type Description Default
data Union[str, dict, GeoDataFrame]

The GeoDataFrame to filter.

required
geom_type str

The geometry type to filter by.

required
output Optional[str]

The file path to save the filtered GeoDataFrame. Defaults to None.

None
**kwargs Any

Additional keyword arguments to pass to the GeoDataFrame.read_file method.

{}

Returns:

Type Description
GeoDataFrame

The filtered GeoDataFrame.

find_closest_date(target_date, date_list, fmt='%Y-%m-%d')

Finds the closest date string in a list of date strings to a given target date.

Parameters:

Name Type Description Default
target_date str

The reference date string to compare against.

required
date_list List[str]

A list of date strings to search.

required
fmt str

The date format used for parsing. Defaults to "%Y-%m-%d".

'%Y-%m-%d'

Returns:

Type Description
Optional[str]

Optional[str]: The date string from date_list that is closest to target_date, or None if date_list is empty or invalid.

find_files(input_dir, ext=None, fullpath=True, recursive=True, include_hidden=False)

Find files in a directory.

Parameters:

Name Type Description Default
input_dir str

The input directory.

required
ext str

The file extension to match. Defaults to None.

None
fullpath bool

Whether to return the full path. Defaults to True.

True
recursive bool

Whether to search recursively. Defaults to True.

True
include_hidden bool

Whether to include hidden files. Defaults to False.

False

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.

gdb_layer_names(gdb_path)

Get a list of layer names in a File Geodatabase (GDB).

Parameters:

Name Type Description Default
gdb_path str

The path to the File Geodatabase (GDB).

required

Returns:

Type Description
List[str]

A list of layer names in the GDB.

gdb_to_vector(gdb_path, out_dir, layers=None, filenames=None, gdal_driver='GPKG', file_extension=None, overwrite=False, quiet=False, **kwargs)

Converts layers from a File Geodatabase (GDB) to a vector format.

Parameters:

Name Type Description Default
gdb_path str

The path to the File Geodatabase (GDB).

required
out_dir str

The output directory to save the converted files.

required
layers Optional[List[str]]

A list of layer names to convert. If None, all layers will be converted. Default is None.

None
filenames Optional[List[str]]

A list of output file names. If None, the layer names will be used as the file names. Default is None.

None
gdal_driver str

The GDAL driver name for the output vector format. Default is "GPKG".

'GPKG'
file_extension Optional[str]

The file extension for the output files. If None, it will be determined automatically based on the gdal_driver. Default is None.

None
overwrite bool

Whether to overwrite the existing output files. Default is False.

False
quiet bool

If True, suppress the log output. Defaults to False.

False

Returns:

Type Description
None

None

gdf_bounds(gdf, return_geom=False)

Returns the bounding box of a GeoDataFrame.

Parameters:

Name Type Description Default
gdf GeoDataFrame

A GeoDataFrame.

required
return_geom bool

Whether to return the bounding box as a GeoDataFrame. Defaults to False.

False

Returns:

Type Description

A bounding box in the form of a list (minx, miny, maxx, maxy) or GeoDataFrame.

gdf_centroid(gdf, return_geom=False)

Returns the centroid of a GeoDataFrame.

Parameters:

Name Type Description Default
gdf GeoDataFrame

A GeoDataFrame.

required
return_geom bool

Whether to return the bounding box as a GeoDataFrame. Defaults to False.

False

Returns:

Type Description

A bounding box in the form of a list (lon, lat) or GeoDataFrame.

gdf_geom_type(gdf, first_only=True)

Returns the geometry type of a GeoDataFrame.

Parameters:

Name Type Description Default
gdf GeoDataFrame

A GeoDataFrame.

required
first_only bool

Whether to return the geometry type of the f irst feature in the GeoDataFrame. Defaults to True.

True

Returns:

Type Description

The geometry type of the GeoDataFrame, such as Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon. For more info, see https://shapely.readthedocs.io/en/stable/manual.html

gdf_to_bokeh(gdf)

Function to convert a GeoPandas GeoDataFrame to a Bokeh ColumnDataSource object.

:param: (GeoDataFrame) gdf: GeoPandas GeoDataFrame with polygon(s) under the column name 'geometry.'

:return: ColumnDataSource for Bokeh.

gdf_to_df(gdf, drop_geom=True)

Converts a GeoDataFrame to a pandas DataFrame.

Parameters:

Name Type Description Default
gdf GeoDataFrame

A GeoDataFrame.

required
drop_geom bool

Whether to drop the geometry column. Defaults to True.

True

Returns:

Type Description

A pandas DataFrame containing the GeoDataFrame.

gdf_to_geojson(gdf, out_geojson=None, epsg=None, tuple_to_list=False, encoding='utf-8')

Converts a GeoDataFame to GeoJSON.

Parameters:

Name Type Description Default
gdf GeoDataFrame

A GeoPandas GeoDataFrame.

required
out_geojson str

File path to he output GeoJSON. Defaults to None.

None
epsg str

An EPSG string, e.g., "4326". Defaults to None.

None
tuple_to_list bool

Whether to convert tuples to lists. Defaults to False.

False
encoding str

The encoding to use for the GeoJSON. Defaults to "utf-8".

'utf-8'

Raises:

Type Description
TypeError

When the output file extension is incorrect.

Exception

When the conversion fails.

Returns:

Type Description
Optional[dict]

When out_json is None returns a dict.

gedi_download_file(url, filename=None, username=None, password=None)

Downloads a file from the given URL and saves it to the specified filename. If no filename is provided, the name of the file from the URL will be used.

Parameters:

Name Type Description Default
url str

The URL of the file to download. e.g., https://daac.ornl.gov/daacdata/gedi/GEDI_L4A_AGB_Density_V2_1/data/GEDI04_A_2019298202754_O04921_01_T02899_02_002_02_V002.h5

required
filename str

The name of the file to save the downloaded content to. Defaults to None.

None
username str

Username for authentication. Can also be set using the EARTHDATA_USERNAME environment variable. Defaults to None. Create an account at https://urs.earthdata.nasa.gov

None
password str

Password for authentication. Can also be set using the EARTHDATA_PASSWORD environment variable. Defaults to None.

None

Returns:

Type Description
None

None

gedi_download_files(urls, outdir=None, filenames=None, username=None, password=None, overwrite=False)

Downloads files from the given URLs and saves them to the specified directory. If no directory is provided, the current directory will be used. If no filenames are provided, the names of the files from the URLs will be used.

Parameters:

Name Type Description Default
urls List[str]

The URLs of the files to download. e.g., ["https://example.com/file1.txt", "https://example.com/file2.txt"]

required
outdir str

The directory to save the downloaded files to. Defaults to None.

None
filenames str

The names of the files to save the downloaded content to. Defaults to None.

None
username str

Username for authentication. Can also be set using the EARTHDATA_USERNAME environment variable. Defaults to None. Create an account at https://urs.earthdata.nasa.gov

None
password str

Password for authentication. Can also be set using the EARTHDATA_PASSWORD environment variable. Defaults to None.

None
overwrite bool

Whether to overwrite the existing output files. Default is False.

False

Returns:

Type Description
None

None

Searches for GEDI data using the Common Metadata Repository (CMR) API. The source code for this function is adapted from https://github.com/ornldaac/gedi_tutorials. Credits to ORNL DAAC and Rupesh Shrestha.

Parameters:

Name Type Description Default
roi Any

A list, tuple, or file path representing the bounding box coordinates in the format (min_lon, min_lat, max_lon, max_lat), or a GeoDataFrame containing the region of interest geometry.

required
start_date Optional[str]

The start date of the temporal range to search for data in the format 'YYYY-MM-DD'.

None
end_date Optional[str]

The end date of the temporal range to search for data in the format 'YYYY-MM-DD'.

None
add_roi bool

A boolean value indicating whether to include the region of interest as a granule in the search results. Default is False.

False
return_type str

The type of the search results to return. Must be one of 'df' (DataFrame), 'gdf' (GeoDataFrame), or 'csv' (CSV file). Default is 'gdf'.

'gdf'
output Optional[str]

The file path to save the CSV output when return_type is 'csv'. Optional and only applicable when return_type is 'csv'.

None
sort_filesize bool

A boolean value indicating whether to sort the search results.

False
**kwargs Any

Additional keyword arguments to be passed to the CMR API.

{}

Returns:

Type Description
Union[DataFrame, None]

The search results as a pandas DataFrame (return_type='df'), geopandas GeoDataFrame

Union[DataFrame, None]

(return_type='gdf'), or a CSV file (return_type='csv').

Raises:

Type Description
ValueError

If roi is not a list, tuple, or file path.

gedi_subset(spatial=None, start_date=None, end_date=None, out_dir=None, collection=None, variables=['all'], max_results=None, username=None, password=None, overwrite=False, **kwargs)

Subsets GEDI data using the Harmony API.

Parameters:

Name Type Description Default
spatial Union[str, GeoDataFrame, List[float]]

Spatial extent for subsetting. Can be a file path to a shapefile, a GeoDataFrame, or a list of bounding box coordinates [minx, miny, maxx, maxy]. Defaults to None.

None
start_date str

Start date for subsetting in 'YYYY-MM-DD' format. Defaults to None.

None
end_date str

End date for subsetting in 'YYYY-MM-DD' format. Defaults to None.

None
out_dir str

Output directory to save the subsetted files. Defaults to None, which will use the current working directory.

None
collection Collection

GEDI data collection. If not provided, the default collection with DOI '10.3334/ORNLDAAC/2056' will be used. Defaults to None.

None
variables List[str]

List of variable names to subset. Defaults to ['all'], which subsets all available variables.

['all']
max_results int

Maximum number of results to return. Defaults to None, which returns all results.

None
username str

Earthdata username. Defaults to None, which will attempt to read from the 'EARTHDATA_USERNAME' environment variable.

None
password str

Earthdata password. Defaults to None, which will attempt to read from the 'EARTHDATA_PASSWORD' environment variable.

None
overwrite bool

Whether to overwrite existing files in the output directory. Defaults to False.

False
**kwargs Any

Additional keyword arguments to pass to the Harmony API request.

{}

Raises:

Type Description
ImportError

If the 'harmony' package is not installed.

ValueError

If the 'spatial', 'start_date', or 'end_date' arguments are not valid.

Returns:

Type Description

None.

generate_index_html(directory, output='index.html')

Generates an HTML file named 'index.html' in the specified directory, listing all files in that directory as clickable links.

Parameters:

Name Type Description Default
directory str

The path to the directory for which to generate the index.html file.

required
output str

The name of the output HTML file. Defaults to "index.html".

'index.html'

Returns:

Type Description
None

None

generate_latlon_grid(extent, dx=0.1, dy=0.1, crs='EPSG:4326', output=None)

Generate a rectangular lat/lon grid as polygons over a given extent.

Parameters

extent : tuple (xmin, ymin, xmax, ymax) in degrees, e.g. (-180, -60, 180, 85) dx : float Longitude interval in degrees (cell width) dy : float Latitude interval in degrees (cell height) crs : str or dict Coordinate reference system for the output GeoDataFrame

Returns

GeoDataFrame Columns: id, lon_min, lat_min, lon_max, lat_max, geometry

geojson_bounds(geojson)

Calculate the bounds of a GeoJSON object.

This function uses the shapely library to calculate the bounds of a GeoJSON object. If the shapely library is not installed, it will print a message and return None.

Parameters:

Name Type Description Default
geojson dict

A dictionary representing a GeoJSON object.

required

Returns:

Type Description
Optional[list]

A list of bounds (minx, miny, maxx, maxy) if shapely is installed, None otherwise.

geojson_to_df(in_geojson, encoding='utf-8', drop_geometry=True)

Converts a GeoJSON object to a pandas DataFrame.

Parameters:

Name Type Description Default
in_geojson str | dict

The input GeoJSON file or dict.

required
encoding str

The encoding of the GeoJSON object. Defaults to "utf-8".

'utf-8'
drop_geometry bool

Whether to drop the geometry column. Defaults to True.

True

Raises:

Type Description
FileNotFoundError

If the input GeoJSON file could not be found.

Returns:

Type Description

A pandas DataFrame containing the GeoJSON object.

geojson_to_gdf(in_geojson, encoding='utf-8', **kwargs)

Converts a GeoJSON object to a geopandas GeoDataFrame.

Parameters:

Name Type Description Default
in_geojson str | dict

The input GeoJSON file or GeoJSON object as a dict.

required
encoding str

The encoding of the GeoJSON object. Defaults to "utf-8".

'utf-8'

Returns:

Type Description

A GeoPandas GeoDataFrame containing the GeoJSON object.

geojson_to_gpkg(in_geojson, out_gpkg, **kwargs)

Converts a GeoJSON object to GeoPackage.

Parameters:

Name Type Description Default
in_geojson str | dict

The input GeoJSON file or dict.

required
out_gpkg str

The output GeoPackage path.

required

geojson_to_mbtiles(input_file, output_file, layer_name=None, options=None, quiet=False)

Converts vector data to .mbtiles using Tippecanoe.

Parameters:

Name Type Description Default
input_file str

Path to the input vector data file (e.g., .geojson).

required
output_file str

Path to the output .mbtiles file.

required
layer_name Optional[str]

Optional name for the layer. Defaults to None.

None
options Optional[List[str]]

List of additional arguments for tippecanoe. For example '-zg' for auto maxzoom. Defaults to None.

None
quiet bool

If True, suppress the log output. Defaults to False.

False

Returns:

Type Description
Optional[str]

Output from the Tippecanoe command, or None if there was an error or if Tippecanoe is not installed.

Raises:

Type Description
CalledProcessError

If there's an error executing the tippecanoe command.

geojson_to_pmtiles(input_file, output_file=None, layer_name=None, projection='EPSG:4326', overwrite=False, options=None, quiet=False)

Converts vector data to PMTiles using Tippecanoe.

Parameters:

Name Type Description Default
input_file str

Path to the input vector data file (e.g., .geojson).

required
output_file str

Path to the output .mbtiles file.

None
layer_name Optional[str]

Optional name for the layer. Defaults to None.

None
projection Optional[str]

Projection for the output PMTiles file. Defaults to "EPSG:4326".

'EPSG:4326'
overwrite bool

If True, overwrite the existing output file. Defaults to False.

False
options Optional[List[str]]

List of additional arguments for tippecanoe. Defaults to None. To reduce the size of the output file, use '-zg' or '-z max-zoom'.

None
quiet bool

If True, suppress the log output. Defaults to False.

False

Returns:

Type Description
Optional[str]

Output from the Tippecanoe command, or None if there was an error or if Tippecanoe is not installed.

Raises:

Type Description
CalledProcessError

If there's an error executing the tippecanoe command.

geojson_to_shp(in_geojson, out_shp, **kwargs)

Converts a GeoJSON object to GeoPandas GeoDataFrame.

Parameters:

Name Type Description Default
in_geojson str | dict

The input GeoJSON file or dict.

required
out_shp str

The output shapefile path.

required

geojsonl_to_parquet_batch(input_dir, output_dir, batch_size=50, file_ext='.json', filename_predix='batch_', **kwargs)

Convert JSON Lines files to multiple GeoParquet files, with each GeoParquet file containing data from a specified number of JSON Lines files.

Parameters:

Name Type Description Default
input_dir str

Directory containing JSON Lines files to convert

required
output_dir str

Directory for output GeoParquet files

required
batch_size int

Number of JSON Lines files to combine in each GeoParquet file. Defaults to 50.

50
file_ext str

File extension of the input files. Defaults to ".json".

'.json'
filename_predix str

Prefix for the output GeoParquet files. Defaults to "batch_".

'batch_'
**kwargs Any

Additional keyword arguments to pass to the to_parquet function of GeoDataFrame.

{}

geom_type(in_geojson, encoding='utf-8')

Returns the geometry type of a GeoJSON object.

Parameters:

Name Type Description Default
in_geojson dict

A GeoJSON object.

required
encoding str

The encoding of the GeoJSON object. Defaults to "utf-8".

'utf-8'

Returns:

Type Description

The geometry type of the GeoJSON object, such as Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon. For more info, see https://shapely.readthedocs.io/en/stable/manual.html

geometry_bounds(geometry, decimals=4)

Returns the bounds of a geometry.

Parameters:

Name Type Description Default
geometry dict

A GeoJSON geometry.

required
decimals int

The number of decimal places to round the bounds to. Defaults to 4.

4

Returns:

Type Description

A list of bounds in the form of [minx, miny, maxx, maxy].

get_3dep_dem(geometry, resolution=30, src_crs=None, output=None, dst_crs='EPSG:5070', to_cog=False, overwrite=False, **kwargs)

Get DEM data at any resolution from 3DEP.

Parameters:

Name Type Description Default
geometry Polygon | MultiPolygon | tuple

It can be a polygon or a bounding box of form (xmin, ymin, xmax, ymax).

required
resolution int

arget DEM source resolution in meters. Defaults to 30.

30
src_crs str

The spatial reference system of the input geometry. Defaults to "EPSG:4326".

None
output str

The output GeoTIFF file. Defaults to None.

None
dst_crs str

The spatial reference system of the output GeoTIFF file. Defaults to "EPSG:5070".

'EPSG:5070'
to_cog bool

Convert to Cloud Optimized GeoTIFF. Defaults to False.

False
overwrite bool

Whether to overwrite the output file if it exists. Defaults to False.

False

Returns:

Type Description

DEM at the specified resolution in meters and CRS as an xarray.DataArray.

get_api_key(name=None, key=None)

Retrieves an API key. If a key is provided, it is returned directly. If a name is provided, the function attempts to retrieve the key from user data (if running in Google Colab) or from environment variables.

Parameters:

Name Type Description Default
name Optional[str]

The name of the key to retrieve. Defaults to None.

None
key Optional[str]

The key to return directly. Defaults to None.

None

Returns:

Type Description
Optional[str]

The retrieved key, or None if no key was found.

get_bounds(geometry, north_up=True, transform=None)

Bounding box of a GeoJSON geometry, GeometryCollection, or FeatureCollection. left, bottom, right, top not xmin, ymin, xmax, ymax If not north_up, y will be switched to guarantee the above. Source code adapted from https://github.com/mapbox/rasterio/blob/master/rasterio/features.py#L361

Parameters:

Name Type Description Default
geometry dict

A GeoJSON dict.

required
north_up bool

. Defaults to True.

True
transform [type]

. Defaults to None.

None

Returns:

Type Description
Tuple[float, float, float, float]

A list of coordinates representing [left, bottom, right, top].

get_census_dict(reset=False)

Returns a dictionary of Census data.

Parameters:

Name Type Description Default
reset bool

Reset the dictionary. Defaults to False.

False

Returns:

Type Description

A dictionary of Census data.

get_center(geometry, north_up=True, transform=None)

Get the centroid of a GeoJSON.

Parameters:

Name Type Description Default
geometry dict

A GeoJSON dict.

required
north_up bool

. Defaults to True.

True
transform [type]

. Defaults to None.

None

Returns:

Type Description
Tuple[float, float]

A coordinate pair in the form [lon, lat].

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.

get_direct_url(url)

Get the direct URL for a given URL.

Parameters:

Name Type Description Default
url str

The URL to get the direct URL for.

required

Returns:

Type Description

The direct URL.

get_ee_tile_url(asset_id, vis_params=None, endpoint=None)

Get the tile URL for an Earth Engine asset.

Parameters:

Name Type Description Default
asset_id str

The Earth Engine asset ID.

required
vis_params Optional[Union[str, dict]]

The visualization parameters.

None
endpoint Optional[str]

The endpoint to use for the tile request. Set to "default" to use the default endpoint.

None

Returns:

Type Description
str

The tile URL.

Raises:

Type Description
ValueError

If the asset ID is not a valid Earth Engine asset ID.

ValueError

If the visualization parameters are not a valid JSON string.

ValueError

If the endpoint is not a valid URL.

ValueError

If the data type is not supported.

get_env_var(key)

Retrieves an environment variable or Colab secret for the given key.

Colab secrets have precedence over environment variables.

Parameters:

Name Type Description Default
key str

The key that's used to fetch the environment variable.

required

Returns:

Type Description
Optional[str]

The retrieved key, or None if no environment variable was found.

get_gdal_drivers()

Get a list of available driver names in the GDAL library.

Returns:

Type Description
List[str]

A list of available driver names.

get_gdal_file_extension(driver_name)

Get the file extension corresponding to a driver name in the GDAL library.

Parameters:

Name Type Description Default
driver_name str

The name of the driver.

required

Returns:

Type Description
Optional[str]

The file extension corresponding to the driver name, or None if the driver is not found or does not have a specific file extension.

get_geometry_coords(row, geom, coord_type, shape_type, mercator=False)

Returns the coordinates ('x' or 'y') of edges of a Polygon exterior.

:param: (GeoPandas Series) row : The row of each of the GeoPandas DataFrame. :param: (str) geom : The column name. :param: (str) coord_type : Whether it's 'x' or 'y' coordinate. :param: (str) shape_type

get_geometry_type(in_geojson)

Get the geometry type of a GeoJSON file.

Parameters:

Name Type Description Default
in_geojson str | dict

The path to the GeoJSON file or a GeoJSON dictionary.

required

Returns:

Type Description
str

The geometry type. Can be one of "Point", "LineString", "Polygon", "MultiPoint", "MultiLineString", "MultiPolygon", "GeometryCollection", or "Unknown".

get_google_map(map_type='HYBRID', show=True, api_key=None, backend='ipyleaflet', **kwargs)

Gets Google basemap tile layer.

Parameters:

Name Type Description Default
map_type str

Can be one of "ROADMAP", "SATELLITE", "HYBRID" or "TERRAIN". Defaults to 'HYBRID'.

'HYBRID'
show bool

Whether to add the layer to the map. Defaults to True.

True
api_key str

The Google Maps API key. Defaults to None.

None
**kwargs Any

Additional arguments to pass to ipyleaflet.TileLayer().

{}

get_google_map_tile_providers(language='en-Us', region='US', api_key=None, **kwargs)

Generates a dictionary of Google Map tile providers for different map types.

Parameters:

Name Type Description Default
language str

An IETF language tag that specifies the language used to display information on the tiles, such as 'zh-Cn'. Defaults to 'en-Us'.

'en-Us'
region str

A Common Locale Data Repository region identifier (two uppercase letters) that represents the physical location of the user. Defaults to 'US'.

'US'
api_key str

The API key to use for the Google Maps API. If not provided, it will try to get it from the environment or Colab user data with the key 'GOOGLE_MAPS_API_KEY'. Defaults to None.

None
**kwargs Any

Additional parameters to pass to the map generation. For more info, visit https://bit.ly/3UhbZKU

{}

Returns:

Type Description
Dict[str, Any]

A dictionary where the keys are the map types and the values are tile providers.

Dict[str, Any]

('roadmap', 'satellite', 'terrain', 'hybrid')

Dict[str, Any]

and the values are the corresponding GoogleMapsTileProvider objects.

get_google_maps_api_key(key='GOOGLE_MAPS_API_KEY')

Retrieves the Google Maps API key from the environment or Colab user data.

Parameters:

Name Type Description Default
key str

The name of the environment variable or Colab user data key where the API key is stored. Defaults to 'GOOGLE_MAPS_API_KEY'.

'GOOGLE_MAPS_API_KEY'

Returns:

Type Description
Optional[str]

The API key, or None if it could not be found.

get_image_colormap(image, index=1)

Retrieve the colormap from an image.

Parameters:

Name Type Description Default
image (str, DatasetReader, DataArray)

The input image. It can be: - A file path to a raster image (string). - A rasterio dataset. - A rioxarray DataArray.

required
index int

The band index to retrieve the colormap from (default is 1).

1

Returns:

Type Description

A dictionary representing the colormap (value: (R, G, B, A)), or None if no colormap is found.

Raises:

Type Description
ValueError

If the input image type is unsupported.

get_local_tile_layer(source, port='default', debug=False, indexes=None, colormap=None, vmin=None, vmax=None, nodata=None, attribution=None, tile_format='ipyleaflet', layer_name='Local COG', client_args={'cors_all': False}, return_client=False, quiet=False, **kwargs)

Generate an ipyleaflet/folium TileLayer from a local raster dataset or remote Cloud Optimized GeoTIFF (COG). If you are using this function in JupyterHub on a remote server and the raster does not render properly, try running the following two lines before calling this function:

1
2
import os
os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = 'proxy/{port}'

Parameters:

Name Type Description Default
source str

The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF.

required
port str

The port to use for the server. Defaults to "default".

'default'
debug bool

If True, the server will be started in debug mode. Defaults to False.

False
indexes int

The band(s) to use. Band indexing starts at 1. Defaults to None.

None
colormap str

The name of the colormap from matplotlib to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale.

None
vmin float

The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None.

None
vmax float

The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None.

None
nodata float

The value from the band to use to interpret as not valid data. Defaults to None.

None
attribution str

Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None.

None
tile_format str

The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet".

'ipyleaflet'
layer_name str

The layer name to use. Defaults to None.

'Local COG'
client_args dict

Additional arguments to pass to the TileClient. Defaults to {}.

{'cors_all': False}
return_client bool

If True, the tile client will be returned. Defaults to False.

False
quiet bool

If True, the error messages will be suppressed. Defaults to False.

False

Returns:

Type Description

An ipyleaflet.TileLayer or folium.TileLayer.

get_local_tile_url(source, port='default', indexes=None, colormap=None, vmin=None, vmax=None, nodata=None, client_args={'cors_all': False}, return_client=False, **kwargs)

Generate an ipyleaflet/folium TileLayer from a local raster dataset or remote Cloud Optimized GeoTIFF (COG). If you are using this function in JupyterHub on a remote server and the raster does not render properly, try running the following two lines before calling this function:

1
2
import os
os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = 'proxy/{port}'

Parameters:

Name Type Description Default
source str

The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF.

required
port str

The port to use for the server. Defaults to "default".

'default'
indexes int

The band(s) to use. Band indexing starts at 1. Defaults to None.

None
colormap str

The name of the colormap from matplotlib to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale.

None
vmin float

The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None.

None
vmax float

The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None.

None
nodata float

The value from the band to use to interpret as not valid data. Defaults to None.

None
client_args dict

Additional arguments to pass to the TileClient. Defaults to {}.

{'cors_all': False}
return_client bool

If True, the tile client will be returned. Defaults to False.

False

Returns:

Type Description

An ipyleaflet.TileLayer or folium.TileLayer.

get_mapillary_image_url(image_id, resolution='original', access_token=None, **kwargs)

Retrieves the URL of a Mapillary image.

Parameters:

Name Type Description Default
image_id str

The ID of the Mapillary image.

required
resolution str

The resolution of the image. Can be 256, 1024, 2048, or original. Defaults to "original".

'original'
access_token str

The access token for the Mapillary API. Defaults to None.

None
**kwargs Any

Additional keyword arguments for the request.

{}

Raises:

Type Description
ValueError

If no access token is provided.

Returns:

Type Description
Optional[str]

The URL of the Mapillary image, or None if an error occurs.

get_mapillary_image_widget(image_id, style='photo', width=800, height=600, frame_border=0, **kwargs)

Creates an iframe widget to display a Mapillary image.

Parameters:

Name Type Description Default
image_id str

The ID of the Mapillary image.

required
style str

The style of the image. Can be "photo", "classic", "split". Defaults to "photo".

'photo'
width int

The width of the iframe. Defaults to 800.

800
height int

The height of the iframe. Defaults to 600.

600
frame_border int

The frame border of the iframe. Defaults to 0.

0
**kwargs Any

Additional keyword arguments for the widget.

{}

Returns:

Type Description
HTML

An iframe widget displaying the Mapillary image.

get_max_pixel_coords(geotiff_path, band_idx=1, roi=None, dst_crs='EPSG:4326', output=None, return_gdf=True, **kwargs)

Find the geographic coordinates of the maximum pixel value in a GeoTIFF.

Parameters:

Name Type Description Default
geotiff_path str

Path to the GeoTIFF file.

required
band_idx int

Band index to use (default is 1).

1
roi str

Path to a vector dataset containing the region of interest (default is None).

None
dst_crs str

Desired output coordinate system in EPSG format (e.g., "EPSG:4326").

'EPSG:4326'
output str

Path to save the output GeoDataFrame (default is None).

None
return_gdf bool

Whether to return a GeoDataFrame (default is True).

True

Returns:

Type Description

Maximum pixel value and its geographic coordinates in the specified CRS.

get_nhd(geometry, geo_crs=4326, xy=True, buffer=0.001, dataset='wbd08', predicate='intersects', sort_attr=None, **kwargs)

Fetches National Hydrography Dataset (NHD) data based on the provided geometry.

Parameters:

Name Type Description Default
geometry Union[GeoDataFrame, str, List[float], Tuple[float, float, float, float]]

The geometry to query the NHD data. It can be a GeoDataFrame, a file path, or coordinates.

required
geo_crs int

The coordinate reference system (CRS) of the geometry (default is 4326).

4326
xy bool

Whether to use x, y coordinates (default is True).

True
buffer float

The buffer distance around the centroid point (default is 0.001 degrees).

0.001
dataset str

The NHD dataset to query (default is "wbd08").

'wbd08'
predicate str

The spatial predicate to use for the query (default is "intersects").

'intersects'
sort_attr Optional[str]

The attribute to sort the results by (default is None).

None
**kwargs Any

Additional keyword arguments to pass to the WaterData.bygeom method.

{}

Returns:

Type Description
Optional[GeoDataFrame]

The fetched NHD data as a GeoDataFrame, or None if an error occurs.

Raises:

Type Description
ImportError

If the pynhd package is not installed.

ValueError

If the geometry type is unsupported.

get_nhd_basins(feature_ids, fsource='nwissite', split_catchment=False, simplified=True, **kwargs)

Get NHD basins for a list of station IDs.

Parameters:

Name Type Description Default
feature_ids str | list

Target feature ID(s).

required
fsource str

The name of feature(s) source, defaults to nwissite. The valid sources are: * 'comid' for NHDPlus comid. * 'ca_gages' for Streamgage catalog for CA SB19 * 'gfv11_pois' for USGS Geospatial Fabric V1.1 Points of Interest * 'huc12pp' for HUC12 Pour Points * 'nmwdi-st' for New Mexico Water Data Initiative Sites * 'nwisgw' for NWIS Groundwater Sites * 'nwissite' for NWIS Surface Water Sites * 'ref_gage' for geoconnex.us reference gauges * 'vigil' for Vigil Network Data * 'wade' for Water Data Exchange 2.0 Sites * 'WQP' for Water Quality Portal

'nwissite'
split_catchment bool

If True, split basins at their outlet locations

False
simplified bool

If True, return a simplified version of basin geometries. Default to True.

True

Raises:

Type Description
ImportError

If pynhd is not installed.

Returns:

Type Description

NLDI indexed basins in EPSG:4326. If some IDs don't return any features a list of missing ID(s) are returned as well.

get_nwi(geometry, in_sr='4326', out_sr='3857', spatial_rel='esriSpatialRelIntersects', return_geometry=True, out_fields=None, clip=False, add_class=False, output=None, **kwargs)

Query the NWI (National Wetlands Inventory) API using various geometry types. https://fwspublicservices.wim.usgs.gov/wetlandsmapservice/rest/services/Wetlands/FeatureServer

Parameters:

Name Type Description Default
geometry dict

The geometry data (e.g., point, polygon, polyline, multipoint, etc.).

required
in_sr str

The input spatial reference (default is EPSG:4326).

'4326'
out_sr str

The output spatial reference (default is EPSG:3857).

'3857'
spatial_rel str

The spatial relationship (default is "esriSpatialRelIntersects").

'esriSpatialRelIntersects'
return_geometry bool

Whether to return the geometry (default is True).

True
out_fields str

The fields to be returned (default is None). Can be "*" or a comma-separated list of fields. The field names start with "Wetlands." or "NWI_Wetland_Codes."

None
clip bool

Whether to clip the geometry to the input geometry (default is False).

False
add_class bool

Whether to add a unique integer class column to the output GeoDataFrame (default is False).

False
output str

The output file path to save the GeoDataFrame (default is None).

None
**kwargs Any

Additional keyword arguments to pass to the API.

{}

Returns:

Type Description
Union[GeoDataFrame, DataFrame, Dict[str, str]]

The queried NWI data as a GeoDataFrame.

get_nwi_by_huc8(huc8=None, geometry=None, out_dir=None, quiet=True, layer='Wetlands', **kwargs)

Fetches National Wetlands Inventory (NWI) data by HUC8 code.

Parameters:

Name Type Description Default
huc8 Optional[str]

The HUC8 code to query the NWI data. It must be a string of length 8.

None
geometry Optional[Union[GeoDataFrame, str]]

The geometry to derive the HUC8 code. It can be a GeoDataFrame or a file path.

None
out_dir Optional[str]

The directory to save the downloaded data. Defaults to a temporary directory.

None
quiet bool

Whether to suppress download progress messages. Defaults to True.

True
layer str

The layer to fetch from the NWI data. It can be one of the following: Wetlands, Watershed, Riparian_Project_Metadata, Wetlands_Historic_Map_Info. Defaults to "Wetlands".

'Wetlands'
**kwargs Any

Additional keyword arguments to pass to the download_file function.

{}

Returns:

Type Description
GeoDataFrame

The fetched NWI data as a GeoDataFrame.

Raises:

Type Description
ValueError

If the HUC8 code is invalid or the layer is not allowed.

get_nwi_year(xy=None, bbox=None, output=None, fields='*', epsg=4326, return_geometry=True)

Get the NWI year from the NWI map service.

Parameters:

Name Type Description Default
xy Optional[tuple]

A tuple of (x, y) coordinates.

None
bbox Optional[list]

A list of [xmin, ymin, xmax, ymax] coordinates.

None
output Optional[str]

The file path to save the output GeoDataFrame.

None
fields str

The fields to return.

'*'
epsg int

The EPSG code of the coordinate system.

4326
return_geometry bool

Whether to return the geometry.

True

get_overlap(img1, img2, overlap, out_img1=None, out_img2=None, to_cog=True)

Get overlapping area of two images.

Parameters:

Name Type Description Default
img1 str

Path to the first image.

required
img2 str

Path to the second image.

required
overlap str

Path to the output overlap area in GeoJSON format.

required
out_img1 str

Path to the cropped image of the first image.

None
out_img2 str

Path to the cropped image of the second image.

None
to_cog bool

Whether to convert the output images to COG.

True

Returns:

Type Description

Path to the overlap area in GeoJSON format.

get_overture_data(overture_type, bbox=None, columns=None, output=None)

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

The fetched overture data as a GeoDataFrame.

Raises:

Type Description
ImportError

If the overture package is not installed.

get_overture_latest_release(patch=False)

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").

False

Returns:

Type Description
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.

get_palettable(types=None)

Get a list of palettable color palettes.

Parameters:

Name Type Description Default
types list

A list of palettable types to return, e.g., types=['matplotlib', 'cartocolors']. Defaults to None.

None

Returns:

Type Description

A list of palettable color palettes.

get_palette_colors(cmap_name=None, n_class=None, hashtag=False)

Get a palette from a matplotlib colormap. See the list of colormaps at https://matplotlib.org/stable/tutorials/colors/colormaps.html.

Parameters:

Name Type Description Default
cmap_name str

The name of the matplotlib colormap. Defaults to None.

None
n_class int

The number of colors. Defaults to None.

None
hashtag bool

Whether to return a list of hex colors. Defaults to False.

False

Returns:

Type Description

A list of hex colors.

get_parquet_geometry_column(input_parquet, db_con=None)

Retrieves the geometry column name from a Parquet file.

This function checks for the presence of a geometry column in the input Parquet file. It looks for columns named "geometry" or "geom" and returns the first match.

Parameters:

Name Type Description Default
input_parquet str

The path to the input Parquet file.

required
db_con Connection

An existing DuckDB connection. If None, a new connection will be created.

None

Returns:

Type Description
str

The name of the geometry column ("geometry" or "geom").

Raises:

Type Description
ValueError

If no recognized geometry column is found in the input Parquet file.

Example

geometry_column = get_parquet_geometry_column("data.parquet") print(geometry_column) "geometry"

get_raster_resolution(image_path)

Get pixel resolution from the raster using rasterio.

Parameters:

Name Type Description Default
image_path str

The path to the raster image.

required

Returns:

Type Description
Tuple[float, float]

A tuple of (x resolution, y resolution).

get_solar_data(lat, lon, radiusMeters=50, view='FULL_LAYERS', requiredQuality='HIGH', pixelSizeMeters=0.1, api_key=None, header=None, out_dir=None, basename=None, quiet=False, **kwargs)

Retrieve solar data for a specific location from Google's Solar API https://developers.google.com/maps/documentation/solar. You need to enable Solar API from https://console.cloud.google.com/google/maps-apis/api-list.

Parameters:

Name Type Description Default
lat float

Latitude of the location.

required
lon float

Longitude of the location.

required
radiusMeters int

Radius in meters for the data retrieval (default is 50).

50
view str

View type (default is "FULL_LAYERS"). For more options, see https://bit.ly/3LazuBi.

'FULL_LAYERS'
requiredQuality str

Required quality level (default is "HIGH").

'HIGH'
pixelSizeMeters float

Pixel size in meters (default is 0.1).

0.1
api_key str

Google API key for authentication (if not provided, checks 'GOOGLE_API_KEY' environment variable).

None
header dict

Additional HTTP headers to include in the request.

None
out_dir str

Directory where downloaded files will be saved.

None
basename str

Base name for the downloaded files (default is generated from imagery date).

None
quiet bool

If True, suppress progress messages during file downloads (default is False).

False
**kwargs Any

Additional keyword arguments to be passed to the download_file function.

{}

Returns:

Type Description
Dict[str, str]

Dict[str, str]: A dictionary mapping file names to their corresponding paths.

get_stac_collections(url, **kwargs)

Retrieve a list of STAC collections from a URL. This function is adapted from https://github.com/mykolakozyr/stacdiscovery/blob/a5d1029aec9c428a7ce7ae615621ea8915162824/app.py#L31. Credits to Mykola Kozyr.

Parameters:

Name Type Description Default
url str

A URL to a STAC catalog.

required
**kwargs Any

Additional keyword arguments to pass to the pystac Client.open() method. See https://pystac-client.readthedocs.io/en/stable/api.html#pystac_client.Client.open

{}

Returns:

Type Description

A list of STAC collections.

get_stac_items(url, collection, limit=None, bbox=None, datetime=None, intersects=None, ids=None, open_args=None, **kwargs)

Retrieve a list of STAC items from a URL and a collection. This function is adapted from https://github.com/mykolakozyr/stacdiscovery/blob/a5d1029aec9c428a7ce7ae615621ea8915162824/app.py#L49. Credits to Mykola Kozyr. Available parameters can be found at https://github.com/radiantearth/stac-api-spec/tree/master/item-search

Parameters:

Name Type Description Default
url str

A URL to a STAC catalog.

required
collection str

A STAC collection ID.

required
limit int

The maximum number of results to return (page size). Defaults to None.

None
bbox tuple

Requested bounding box in the format of (minx, miny, maxx, maxy). Defaults to None.

None
datetime str

Single date+time, or a range ('/' separator), formatted to RFC 3339, section 5.6. Use double dots .. for open date ranges.

None
intersects dict

A dictionary representing a GeoJSON Geometry. Searches items by performing intersection between their geometry and provided GeoJSON geometry. All GeoJSON geometry types must be supported.

None
ids list

A list of item ids to return.

None
open_args dict

A dictionary of arguments to pass to the pystac Client.open() method. Defaults to None.

None
**kwargs Any

Additional keyword arguments to pass to the Catalog.search() method.

{}

Returns:

Type Description

A GeoDataFrame with the STAC items.

get_unique_name(name, names, overwrite=False)

Generates a unique name based on the input name and existing names.

Parameters:

Name Type Description Default
name str

The base name to generate a unique name from.

required
names list

A list of existing names to check against.

required
overwrite bool

If True, the function will return the original name even if it exists in the list. Defaults to False.

False

Returns:

Type Description
str

A unique name based on the input name.

get_vector_column_names(input_vector, db_con=None)

Retrieves the column names from a DuckDB table.

Parameters:

Name Type Description Default
input_vector str

The path to the input vector file (e.g., a Parquet or GeoPackage file).

required
db_con Connection

An existing DuckDB connection. If None, a new connection will be created.

None

Returns:

Type Description

A list of column names from the specified table.

Raises:

Type Description
CatalogException

If the table does not exist.

get_vector_crs(input_vector, db_con=None, return_epsg=False)

Retrieves the Coordinate Reference System (CRS) of a vector file.

This function extracts the CRS information from the metadata of the input vector file.

Parameters:

Name Type Description Default
input_vector str

The path to the input vector file.

required
db_con Connection

An existing DuckDB connection. If None, a new connection will be created.

None
return_epsg bool

Whether to return the EPSG code of the CRS. Defaults to False.

False

Returns:

Type Description

Union[dict, int]: The CRS information as a dictionary or the EPSG code as an integer.

Raises:

Type Description
ValueError

If the CRS information is not available in the input vector file.

Example

crs = get_vector_crs("data.gpkg", return_epsg=True) print(crs) 4326

get_vector_metadata(input_vector, db_con=None)

Retrieves metadata for a vector file.

This function uses DuckDB with the spatial extension to extract metadata about the layers in the input vector file.

Parameters:

Name Type Description Default
input_vector str

The path to the input vector file.

required
db_con Connection

An existing DuckDB connection. If None, a new connection will be created.

None

Returns:

Type Description

A dictionary containing metadata about the vector file.

Raises:

Type Description
ValueError

If the input vector file does not exist.

Example

metadata = get_vector_metadata("data.gpkg") print(metadata) {'geometry_fields': [{'name': 'geom', 'crs': {'auth_name': 'EPSG', 'auth_code': '4326'}}], ...}

get_wayback_layers(url=None)

Retrieve all layer dates and tile IDs from the ArcGIS Wayback WMTS capabilities URL.

Parameters:

Name Type Description Default
url str

WMTS capabilities URL. Default to https://wayback.maptiles.arcgis.com/arcgis/rest/services/world_imagery/mapserver/wmts/1.0.0/wmtscapabilities.xml

None

Returns:

Name Type Description
dict dict

A dictionary where keys are layer dates (e.g., '2023-01-11') and values are corresponding tile IDs (e.g., '11475').

get_wayback_tile_dict(layers=None)

Generates a dictionary of Wayback Map Tiles.

Parameters:

Name Type Description Default
layers dict

A dictionary of layers. Defaults to None.

None

Returns:

Name Type Description
dict dict

A dictionary of Wayback Map Tiles.

get_wayback_tile_url(date=None, layers=None, quiet=False)

Generates a URL for Wayback Map Tiles.

Parameters:

Name Type Description Default
date str

The date for which to retrieve the tile URL in 'YYYY-MM-DD' format. If None, the latest available date is used.

None
layers dict

A dictionary of available layers keyed by date. If None, the default layers are retrieved.

None
quiet bool

If True, does not print any messages. Defaults to False.

False

Raises:

Type Description
ValueError

If the provided date is not available in the layers.

Notes

If the specified date is not available, the latest date from the layers will be used.

get_wbd(geometry=None, searchText=None, inSR='4326', outSR='3857', digit=8, spatialRel='esriSpatialRelIntersects', return_geometry=True, outFields='*', output=None, **kwargs)

Query the WBD (Watershed Boundary Dataset) API using various geometry types or a GeoDataFrame. https://hydro.nationalmap.gov/arcgis/rest/services/wbd/MapServer

Parameters:

Name Type Description Default
geometry Union[GeoDataFrame, Dict]

The geometry data (GeoDataFrame or geometry dict).

None
inSR str

The input spatial reference (default is EPSG:4326).

'4326'
outSR str

The output spatial reference (default is EPSG:3857).

'3857'
digit int

The digit code for the WBD layer (default is 8).

8
spatialRel str

The spatial relationship (default is "esriSpatialRelIntersects").

'esriSpatialRelIntersects'
return_geometry bool

Whether to return the geometry (default is True).

True
outFields str

The fields to be returned (default is "*").

'*'
output Optional[str]

The output file path to save the GeoDataFrame (default is None).

None
**kwargs Any

Additional keyword arguments to pass to the API.

{}

Returns:

Type Description
Union[GeoDataFrame, DataFrame, Dict[str, str]]

The queried WBD data as a GeoDataFrame or DataFrame.

get_wms_layers(url)

Returns a list of WMS layers from a WMS service.

Parameters:

Name Type Description Default
url str

The URL of the WMS service.

required

Returns:

Type Description

A list of WMS layers.

gif_fading(in_gif, out_gif, duration=1, verbose=True)

Fade in/out the gif.

Parameters:

Name Type Description Default
in_gif str

The input gif file. Can be a directory path or http URL, e.g., "https://i.imgur.com/ZWSZC5z.gif"

required
out_gif str

The output gif file.

required
duration float

The duration of the fading. Defaults to 1.

1
verbose bool

Whether to print the progress. Defaults to True.

True

Raises:

Type Description
FileNotFoundError

Raise exception when the input gif does not exist.

Exception

Raise exception when ffmpeg is not installed.

gif_to_mp4(in_gif, out_mp4)

Converts a gif to mp4.

Parameters:

Name Type Description Default
in_gif str

The input gif file.

required
out_mp4 str

The output mp4 file.

required

gif_to_png(in_gif, out_dir=None, prefix='', verbose=True)

Converts a gif to png.

Parameters:

Name Type Description Default
in_gif str

The input gif file.

required
out_dir str

The output directory. Defaults to None.

None
prefix str

The prefix of the output png files. Defaults to None.

''
verbose bool

Whether to print the progress. Defaults to True.

True

Raises:

Type Description
FileNotFoundError

Raise exception when the input gif does not exist.

Exception

Raise exception when ffmpeg is not installed.

github_delete_asset(username, repository, asset_id, access_token=None)

Deletes an asset from a GitHub release.

Parameters:

Name Type Description Default
username str

GitHub username or organization name.

required
repository str

Name of the GitHub repository.

required
asset_id int

ID of the asset to delete.

required
access_token str

Personal access token for authentication.

None

github_get_release_assets(username, repository, release_id, access_token=None)

Fetches the assets for a given release.

Parameters:

Name Type Description Default
username str

GitHub username or organization name.

required
repository str

Name of the GitHub repository.

required
release_id int

ID of the release to fetch assets for.

required
access_token str

Personal access token for authentication.

None

Returns:

Type Description

List of assets if successful, None otherwise.

github_get_release_id_by_tag(username, repository, tag_name, access_token=None)

Fetches the release ID by tag name for a given GitHub repository.

Parameters:

Name Type Description Default
username str

GitHub username or organization name.

required
repository str

Name of the GitHub repository.

required
tag_name str

Tag name of the release.

required
access_token str

Personal access token for authentication. Defaults to None.

None

Returns:

Type Description

The release ID if found, None otherwise.

github_raw_url(url)

Get the raw URL for a GitHub file.

Parameters:

Name Type Description Default
url str

The GitHub URL.

required

github_upload_asset_to_release(username, repository, release_id, asset_path, quiet=False, access_token=None)

Uploads an asset to a GitHub release.

Parameters:

Name Type Description Default
username str

GitHub username or organization name.

required
repository str

Name of the GitHub repository.

required
release_id int

ID of the release to upload the asset to.

required
asset_path str

Path to the asset file.

required
access_token str

Personal access token for authentication.

None

Returns:

Name Type Description

The response JSON from the GitHub API if the upload is successful.

None

If the upload fails.

google_buildings_csv_to_vector(filename, output=None, **kwargs)

Convert a CSV file containing Google Buildings data to a GeoJSON vector file.

Parameters:

Name Type Description Default
filename str

The path to the input CSV file.

required
output str

The path to the output GeoJSON file. If not provided, the output file will have the same name as the input file with the extension changed to '.geojson'.

None
**kwargs

Additional keyword arguments that are passed to the to_file method of the GeoDataFrame.

{}

Returns:

Type Description
None

None

h5_keys(filename)

Retrieve the keys (dataset names) within an HDF5 file.

Parameters:

Name Type Description Default
filename str

The filename of the HDF5 file.

required

Returns:

Type Description
List[str]

A list of dataset names present in the HDF5 file.

Raises:

Type Description
ImportError

Raised if h5py is not installed.

Example

keys = h5_keys('data.h5') print(keys) [

h5_to_gdf(filenames, dataset, lat='lat_lowestmode', lon='lon_lowestmode', columns=None, crs='EPSG:4326', nodata=None, **kwargs)

Read data from one or multiple HDF5 files and return as a GeoDataFrame.

Parameters:

Name Type Description Default
filenames str or List[str]

The filename(s) of the HDF5 file(s).

required
dataset str

The dataset name within the H5 file(s).

required
lat str

The column name representing latitude. Default is 'lat_lowestmode'.

'lat_lowestmode'
lon str

The column name representing longitude. Default is 'lon_lowestmode'.

'lon_lowestmode'
columns List[str]

List of column names to include. If None, all columns will be included. Default is None.

None
crs str

The coordinate reference system code. Default is "EPSG:4326".

'EPSG:4326'
**kwargs Any

Additional keyword arguments to be passed to the GeoDataFrame constructor.

{}

Returns:

Type Description

A GeoDataFrame containing the data from the H5 file(s).

Raises:

Type Description
ImportError

Raised if h5py is not installed.

ValueError

Raised if the provided filenames argument is not a valid type or if a specified file does not exist.

Example

gdf = h5_to_gdf('data.h5', 'dataset1', 'lat', 'lon', columns=['column1', 'column2'], crs='EPSG:4326') print(gdf.head()) column1 column2 lat lon geometry 0 10 20 40.123456 -75.987654 POINT (-75.987654 40.123456) 1 15 25 40.234567 -75.876543 POINT (-75.876543 40.234567) ...

h5_variables(filename, key)

Retrieve the variables (column names) within a specific key (dataset) in an H5 file.

Parameters:

Name Type Description Default
filename str

The filename of the H5 file.

required
key str

The key (dataset name) within the H5 file.

required

Returns:

Type Description
List[str]

A list of variable names (column names) within the specified key.

Raises:

Type Description
ImportError

Raised if h5py is not installed.

Example

variables = h5_variables('data.h5', 'dataset1') print(variables) ['var1', 'var2', 'var3']

has_transparency(img)

Checks whether an image has transparency.

Parameters:

Name Type Description Default
img object

a PIL Image object.

required

Returns:

Type Description
bool

True if it has transparency, False otherwise.

hex_to_rgb(value='FFFFFF')

Converts hex color to RGB color.

Parameters:

Name Type Description Default
value str

Hex color code as a string. Defaults to 'FFFFFF'.

'FFFFFF'

Returns:

Type Description
Tuple[int, int, int]

RGB color as a tuple.

html_to_gradio(html, width='100%', height='500px', **kwargs)

Converts the map to an HTML string that can be used in Gradio. Removes unsupported elements, such as attribution and any code blocks containing functions. See https://github.com/gradio-app/gradio/issues/3190

Parameters:

Name Type Description Default
width str

The width of the map. Defaults to '100%'.

'100%'
height str

The height of the map. Defaults to '500px'.

'500px'

Returns:

Type Description

The HTML string to use in Gradio.

html_to_streamlit(html, width=800, height=600, responsive=True, scrolling=False, token_name=None, token_value=None, **kwargs)

Renders an HTML file in a Streamlit app. This method is a static Streamlit Component, meaning, no information is passed back from Leaflet on browser interaction.

Parameters:

Name Type Description Default
html str

The HTML file to render. It can a local file path or a URL.

required
width int

Width of the map. Defaults to 800.

800
height int

Height of the map. Defaults to 600.

600
responsive bool

Whether to make the map responsive. Defaults to True.

True
scrolling bool

Whether to allow the map to scroll. Defaults to False.

False
token_name str

The name of the token in the HTML file to be replaced. Defaults to None.

None
token_value str

The value of the token to pass to the HTML file. Defaults to None.

None

Returns:

Type Description

A Streamlit components.html object.

image_bandcount(image, **kwargs)

Get the number of bands in an image.

Parameters:

Name Type Description Default
image str

The input image filepath or URL.

required

Returns:

Type Description

The number of bands in the image.

image_bbox(raster_path, output_file=None, to_crs=None, **kwargs)

Get the bounding box of an image.

Parameters:

Name Type Description Default
raster_path str

The input image filepath or URL.

required
output_file str

The output file path. Defaults to None.

None
to_crs str

The CRS to convert the bounding box to. Defaults to None.

None

image_bounds(image, **kwargs)

Get the bounds of an image.

Parameters:

Name Type Description Default
image str

The input image filepath or URL.

required

Returns:

Type Description

A list of bounds in the form of [(south, west), (north, east)].

image_center(image, **kwargs)

Get the center of an image.

Parameters:

Name Type Description Default
image str

The input image filepath or URL.

required

Returns:

Type Description

A tuple of (latitude, longitude).

image_client(image, **kwargs)

Get a LocalTileserver TileClient from an image.

Parameters:

Name Type Description Default
image str

The input image filepath or URL.

required

Returns:

Type Description

A LocalTileserver TileClient.

image_comparison(img1, img2, label1='1', label2='2', width=704, show_labels=True, starting_position=50, make_responsive=True, in_memory=True, out_html=None)

Create a comparison slider for two images. The source code is adapted from https://github.com/fcakyon/streamlit-image-comparison. Credits to the GitHub user @fcakyon. Users can also use https://juxtapose.knightlab.com to create a comparison slider.

Parameters:

Name Type Description Default
img1 str

Path to the first image. It can be a local file path, a URL, or a numpy array.

required
img2 str

Path to the second image. It can be a local file path, a URL, or a numpy array.

required
label1 str

Label for the first image. Defaults to "1".

'1'
label2 str

Label for the second image. Defaults to "2".

'2'
width int

Width of the component in pixels. Defaults to 704.

704
show_labels bool

Whether to show labels on the images. Default is True.

True
starting_position int

Starting position of the slider as a percentage (0-100). Default is 50.

50
make_responsive bool

Whether to enable responsive mode. Default is True.

True
in_memory bool

Whether to handle pillow to base64 conversion in memory without saving to local. Default is True.

True
out_html str

Whether to handle pillow to base64 conversion in memory without saving to local. Default is True.

None

image_filesize(region, cellsize, bands=1, dtype='uint8', unit='MB', source_crs='epsg:4326', dst_crs='epsg:3857', bbox=False)

Calculate the size of an image in a given region and cell size.

Parameters:

Name Type Description Default
region list

A bounding box in the format of [minx, miny, maxx, maxy].

required
cellsize float

The resolution of the image.

required
bands int

Number of bands. Defaults to 1.

1
dtype str

Data type, such as unit8, float32. For more info, see https://numpy.org/doc/stable/user/basics.types.html. Defaults to 'uint8'.

'uint8'
unit str

The unit of the output. Defaults to 'MB'.

'MB'
source_crs str

The CRS of the region. Defaults to 'epsg:4326'.

'epsg:4326'
dst_crs str

The destination CRS to calculate the area. Defaults to 'epsg:3857'.

'epsg:3857'
bbox bool

Whether to use the bounding box of the region to calculate the area. Defaults to False.

False

Returns:

Type Description

The size of the image in a given unit.

image_geotransform(image, **kwargs)

Get the geotransform of an image.

Parameters:

Name Type Description Default
image str

The input image filepath or URL.

required

Returns:

Type Description

A list of geotransform values.

image_metadata(image, **kwargs)

Get the metadata of an image.

Parameters:

Name Type Description Default
image str

The input image filepath or URL.

required

Returns:

Type Description

A dictionary of image metadata.

image_min_max(image, bands=None)

Computes the minimum and maximum pixel values of an image.

This function opens an image file using xarray and rasterio, optionally selects specific bands, and then computes the minimum and maximum pixel values in the image.

Parameters:

Name Type Description Default
image str

The path to the image file.

required
bands int or list

The band or list of bands to select. If None, all bands are used.

None

Returns:

Type Description
Tuple[float, float]

Tuple[float, float]: The minimum and maximum pixel values in the image.

image_projection(image, **kwargs)

Get the projection of an image.

Parameters:

Name Type Description Default
image str

The input image filepath or URL.

required

Returns:

Type Description

The projection of the image.

image_resolution(image, **kwargs)

Get the resolution of an image.

Parameters:

Name Type Description Default
image str

The input image filepath or URL.

required

Returns:

Type Description

The resolution of the image.

image_set_crs(image, epsg)

Define the CRS of an image.

Parameters:

Name Type Description Default
image str

The input image filepath

required
epsg int

The EPSG code of the CRS to set.

required

image_size(image, **kwargs)

Get the size (width, height) of an image.

Parameters:

Name Type Description Default
image str

The input image filepath or URL.

required

Returns:

Type Description

A tuple of (width, height).

image_to_cog(source, dst_path=None, profile='deflate', BIGTIFF=None, nodata=None, **kwargs)

Converts an image to a COG file.

Parameters:

Name Type Description Default
source str

A dataset path, URL or rasterio.io.DatasetReader object.

required
dst_path str

An output dataset path or or PathLike object. Defaults to None.

None
profile str

COG profile. More at https://cogeotiff.github.io/rio-cogeo/profile. Defaults to "deflate".

'deflate'
BIGTIFF str

Create a BigTIFF file. Can be "IF_SAFER" or "YES". Defaults to None.

None
nodata int, float, or None

NoData value for the output COG. Set to None to prevent any value from being treated as NoData (avoids 255 being changed to 254 in uint8 images). Defaults to None.

None

Raises:

Type Description
ImportError

If rio-cogeo is not installed.

FileNotFoundError

If the source file could not be found.

image_to_geotiff(image, dst_path, dtype=None, to_cog=True, **kwargs)

Converts an image to a GeoTIFF file.

This function takes an image in the form of a rasterio.io.DatasetReader object, and writes it to a GeoTIFF file at the specified destination path. The data type of the output GeoTIFF can be specified. Additional keyword arguments can be passed to customize the GeoTIFF profile.

Parameters:

Name Type Description Default
image DatasetReader

The input image as a rasterio.io.DatasetReader object.

required
dst_path str

The destination path where the GeoTIFF file will be saved.

required
dtype Optional[str]

The data type for the output GeoTIFF file. If None, the data type of the input image will be used. Defaults to None.

None
to_cog bool

Whether to convert the output GeoTIFF to a Cloud Optimized GeoTIFF (COG). Defaults to True.

True
**kwargs

Additional keyword arguments to be included in the GeoTIFF profile.

{}

Raises:

Type Description
ValueError

If the input image is not a rasterio.io.DatasetReader object.

Returns:

Type Description
None

None

image_to_numpy(image)

Converts an image to a numpy array.

Parameters:

Name Type Description Default
image str

A dataset path, URL or rasterio.io.DatasetReader object.

required

Raises:

Type Description
FileNotFoundError

If the provided file could not be found.

Returns:

Type Description

A numpy array.

images_to_tiles(images, names=None, ipyleaflet=True, **kwargs)

Convert a list of images to a dictionary of ipyleaflet.TileLayer objects.

Parameters:

Name Type Description Default
images str | list

The path to a directory of images or a list of image paths.

required
names list

A list of names for the layers. Defaults to None.

None
ipyleaflet bool

Whether to return ipyleaflet.TileLayer objects. Defaults to True.

True
**kwargs Any

Additional arguments to pass to get_local_tile_layer().

{}

Returns:

Type Description
Dict[str, TileLayer]

A dictionary of ipyleaflet.TileLayer objects.

init_duckdb_tiles(data, database_path=':memory:', table_name='features', geom_column='geom', srid=3857, quiet=False, use_view=False, src_crs=None)

Initialize a DuckDB database with spatial data for vector tile serving.

This function creates a DuckDB database and loads spatial data from various sources into a table suitable for serving vector tiles. The geometry is automatically transformed to Web Mercator (EPSG:3857) for tile generation.

Supports all vector formats that DuckDB's ST_Read can handle, including: - GeoJSON (.geojson, .json) - Shapefile (.shp) - GeoPackage (.gpkg) - FlatGeobuf (.fgb) - GeoParquet (.parquet, .geoparquet) - And many more GDAL-supported formats

Parameters:

Name Type Description Default
data

The spatial data to load. Can be: - Path to a vector file (str) - Any format supported by DuckDB's ST_Read - GeoJSON dictionary - GeoDataFrame

required
database_path str

Path to the DuckDB database file. Use ":memory:" for an in-memory database. Defaults to ":memory:".

':memory:'
table_name str

Name of the table to create in the database. Defaults to "features".

'features'
geom_column str

Name of the geometry column. Defaults to "geom".

'geom'
srid int

Target SRID for the geometry. Defaults to 3857 (Web Mercator).

3857
quiet bool

If True, suppress progress messages. Defaults to False.

False
use_view bool

If True and data is a parquet file, create a view instead of a table. Views avoid data duplication but may be slower for tile serving as they query the source file on each request. Only applies to parquet files. Defaults to False.

False
src_crs str

Source CRS of the input data as an EPSG code (e.g., 'EPSG:5070', 'EPSG:4326'). If None, will attempt to auto-detect. Specify this parameter if the data is in a projected CRS that is not Web Mercator. Defaults to None.

None

Returns:

Name Type Description
str str

The path to the created database.

Raises:

Type Description
ImportError

If duckdb is not installed.

Exception

If data loading or transformation fails.

Example

import leafmap

From GeoJSON file

db_path = leafmap.init_duckdb_tiles( ... "data.geojson", ... database_path="tiles.db", ... table_name="buildings" ... )

From Shapefile

db_path = leafmap.init_duckdb_tiles("data.shp", database_path="tiles.db")

From GeoPackage

db_path = leafmap.init_duckdb_tiles("data.gpkg", database_path="tiles.db")

From GeoDataFrame

import geopandas as gpd gdf = gpd.read_file("data.geojson") db_path = leafmap.init_duckdb_tiles(gdf, database_path="tiles.db")

inspector_gui(m, position='topright', opened=True)

Generates a tool GUI template using ipywidgets.

Parameters:

Name Type Description Default
m Map

The leaflet Map object. Defaults to None.

required

Returns:

Name Type Description
ipywidgets

The tool GUI widget.

install_package(package)

Install a Python package.

Parameters:

Name Type Description Default
package str | list

The package name or a GitHub URL or a list of package names or GitHub URLs.

required

is_arcpy()

Check if arcpy is available.

Returns:

Type Description

True if arcpy is available, False otherwise.

is_array(x)

Test whether x is either a numpy.ndarray or xarray.DataArray

is_global_bounds(bounds, tolerance=1.0)

Check if bounds represent global extent.

Parameters:

Name Type Description Default
bounds list

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

required
tolerance float

Tolerance for comparing bounds to global extent. Defaults to 1.0 degree.

1.0

Returns:

Name Type Description
bool

True if bounds are approximately global [-180, -90, 180, 90].

is_jupyterlite()

Check if the current notebook is running on JupyterLite.

Returns:

Type Description

True if the notebook is running on JupyterLite.

is_on_aws()

Check if the current notebook is running on AWS.

Returns:

Type Description

True if the notebook is running on AWS.

is_studio_lab()

Check if the current notebook is running on Studio Lab.

Returns:

Type Description

True if the notebook is running on Studio Lab.

is_tool(name)

Check whether name is on PATH and marked as executable.

json_to_geojson(input_path, output_path)

Converts a JSON file to a GeoJSON file.

Parameters:

Name Type Description Default
input_path str

The file path to the input JSON file.

required
output_path str

The file path to save the output GeoJSON file.

required

Raises:

Type Description
FileNotFoundError

If the input file does not exist.

ValueError

If the input JSON file is not properly formatted.

kml_to_geojson(in_kml, out_geojson=None)

Converts a KML to GeoJSON.

Parameters:

Name Type Description Default
in_kml str

The file path to the input KML.

required
out_geojson str

The file path to the output GeoJSON. Defaults to None.

None

Raises:

Type Description
FileNotFoundError

The input KML could not be found.

TypeError

The output must be a GeoJSON.

kml_to_shp(in_kml, out_shp)

Converts a KML to shapefile.

Parameters:

Name Type Description Default
in_kml str

The file path to the input KML.

required
out_shp str

The file path to the output shapefile.

required

Raises:

Type Description
FileNotFoundError

The input KML could not be found.

TypeError

The output must be a shapefile.

layer_manager_gui(m, position='topright', opened=True, return_widget=False)

Creates a layer manager widget.

Parameters:

Name Type Description Default
m Map

The geemap.Map object.

required
position str

The position of the widget. Defaults to "topright".

'topright'
return_widget bool

Whether to return the widget. Defaults to False.

False

line_to_points(data)

Converts a LineString geometry in a GeoDataFrame into individual points.

Parameters:

Name Type Description Default
data str

A GeoDataFrame containing a LineString geometry.

required

Returns:

Type Description
GeoDataFrame

A new GeoDataFrame where each vertex of the LineString is a Point geometry.

list_palettes(add_extra=False, lowercase=False)

List all available colormaps. See a complete lost of colormaps at https://matplotlib.org/stable/tutorials/colors/colormaps.html.

Returns:

Type Description

The list of colormap names.

lnglat_to_meters(longitude, latitude)

coordinate conversion between lat/lon in decimal degrees to web mercator

Parameters:

Name Type Description Default
longitude float

The longitude.

required
latitude float

The latitude.

required

Returns:

Type Description

A tuple of (x, y) in meters.

local_tile_bands(source)

Get band names from COG.

Parameters:

Name Type Description Default
source str | TileClient

A local COG file path or TileClient

required

Returns:

Type Description
List[str]

A list of band names.

local_tile_pixel_value(lon, lat, tile_client, 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
verbose bool

Print status messages. Defaults to True.

True

Returns:

Type Description
Any

rio-tiler point data.

local_tile_vmin_vmax(source, bands=None, **kwargs)

Get vmin and vmax from COG.

Parameters:

Name Type Description Default
source str | TileClient

A local COG file path or TileClient object.

required
bands str | list

A list of band names. Defaults to None.

None

Raises:

Type Description
ValueError

If source is not a TileClient object or a local COG file path.

Returns:

Type Description
Tuple[float, float]

A tuple of vmin and vmax.

main_toolbar(m)

Creates the main toolbar and adds it to the map.

Parameters:

Name Type Description Default
m Map

The leafmap Map object.

required

make_gif(images, out_gif, ext='jpg', fps=10, loop=0, mp4=False, clean_up=False)

Creates a gif from a list of images.

Parameters:

Name Type Description Default
images list | str

The list of images or input directory to create the gif from.

required
out_gif str

File path to the output gif.

required
ext str

The extension of the images. Defaults to 'jpg'.

'jpg'
fps int

The frames per second of the gif. Defaults to 10.

10
loop int

The number of times to loop the gif. Defaults to 0.

0
mp4 bool

Whether to convert the gif to mp4. Defaults to False.

False

map_tiles_to_geotiff(output, bbox, zoom=None, resolution=None, source='OpenStreetMap', crs='EPSG:3857', to_cog=False, quiet=False, **kwargs)

Download map tiles and convert them to a GeoTIFF. The source is adapted from https://github.com/gumblex/tms2geotiff. Credits to the GitHub user @gumblex.

Parameters:

Name Type Description Default
output str

The output GeoTIFF file.

required
bbox list

The bounding box [minx, miny, maxx, maxy] coordinates in EPSG:4326, e.g., [-122.5216, 37.733, -122.3661, 37.8095]

required
zoom int

The map zoom level. Defaults to None.

None
resolution float

The resolution in meters. Defaults to None.

None
source str

The tile source. It can be one of the following: "OPENSTREETMAP", "ROADMAP", "SATELLITE", "TERRAIN", "HYBRID", or an HTTP URL. Defaults to "OpenStreetMap".

'OpenStreetMap'
crs str

The coordinate reference system. Defaults to "EPSG:3857".

'EPSG:3857'
to_cog bool

Convert to Cloud Optimized GeoTIFF. Defaults to False.

False
quiet bool

Suppress output. Defaults to False.

False
**kwargs Any

Additional arguments to pass to gdal.GetDriverByName("GTiff").Create().

{}

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.

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.

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.

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.

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

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.

maxar_refresh()

Refresh the cached Maxar STAC items.

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.

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.

mbtiles_to_pmtiles(input_file, output_file, max_zoom=99)

Converts mbtiles to pmtiles using the pmtiles package.

Parameters:

Name Type Description Default
input_file str

Path to the input .mbtiles file.

required
output_file str

Path to the output .pmtiles file.

required
max_zoom int

Maximum zoom level for the conversion. Defaults to 99.

99

Returns:

Type Description
Optional[None]

None upon successful completion or when the pmtiles package is not installed.

merge_gifs(in_gifs, out_gif)

Merge multiple gifs into one.

Parameters:

Name Type Description Default
in_gifs str | list

The input gifs as a list or a directory path.

required
out_gif str

The output gif.

required

Raises:

Type Description
Exception

Raise exception when gifsicle is not installed.

merge_rasters(input_dir_or_files, output, input_pattern='*.tif', output_format='GTiff', output_nodata=None, output_options=None, **kwargs)

Merge a directory of rasters or a list of file paths into a single raster.

Parameters:

Name Type Description Default
input_dir_or_files Union[str, List[str]]

The path to the input directory or a list of file paths.

required
output str

The path to the output raster.

required
input_pattern str

The glob pattern to match input files if a directory is provided. Defaults to "*.tif".

'*.tif'
output_format str

The output raster format. Defaults to "GTiff".

'GTiff'
output_nodata float

The nodata value for the output raster. Defaults to None.

None
output_options list

A list of creation options for the output raster. Defaults to ["COMPRESS=DEFLATE"].

None
**kwargs Any

Additional arguments to pass to gdal.WarpOptions.

{}

Raises:

Type Description
ImportError

If GDAL is not installed.

ValueError

If no input files are found.

merge_vector(files, output=None, crs=None, ext='geojson', recursive=False, quiet=False, return_gdf=False, **kwargs)

Merge vector files into a single GeoDataFrame.

Parameters:

Name Type Description Default
files Union[str, List[str]]

A string or a list of file paths to be merged.

required
output str

The file path to save the merged GeoDataFrame.

None
crs str

Optional. The coordinate reference system (CRS) of the output GeoDataFrame.

None
ext str

Optional. The file extension of the input files. Default is 'geojson'.

'geojson'
recursive bool

Optional. If True, search for files recursively in subdirectories. Default is False.

False
quiet bool

Optional. If True, suppresses progress messages. Default is False.

False
return_gdf bool

Optional. If True, returns the merged GeoDataFrame. Default is False.

False
**kwargs Any

Additional keyword arguments to be passed to the gpd.read_file function.

{}

Returns:

Type Description
Optional[GeoDataFrame]

If return_gdf is True, returns the merged GeoDataFrame. Otherwise, returns None.

Raises:

Type Description
TypeError

If files is not a list of file paths.

meters_to_lnglat(x, y)

coordinate conversion between web mercator to lat/lon in decimal degrees

Parameters:

Name Type Description Default
x float

The x coordinate.

required
y float

The y coordinate.

required

Returns:

Type Description

A tuple of (longitude, latitude) in decimal degrees.

mosaic(images, output, ext='tif', recursive=True, merge_args={}, to_cog=True, verbose=True, **kwargs)

Mosaics a list of images into a single image. Inspired by https://bit.ly/3A6roDK.

Parameters:

Name Type Description Default
images str | list

An input directory containing images or a list of images.

required
output str

The output image filepath.

required
ext str

The file extension of the images. Defaults to 'tif'.

'tif'
recursive bool

Whether to recursively search for images in the input directory. Defaults to True.

True
merge_args dict

A dictionary of arguments to pass to the rasterio.merge function. Defaults to {}.

{}
to_cog bool

Whether to convert the output image to a Cloud Optimized GeoTIFF. Defaults to True.

True
verbose bool

Whether to print progress. Defaults to True.

True

mosaic_bounds(url, titiler_endpoint=None, **kwargs)

Get the bounding box of a MosaicJSON.

Parameters:

Name Type Description Default
url str

HTTP URL to a MosaicJSON.

required
titiler_endpoint str

TiTiler endpoint, e.g., "https://titiler.opengeos.org". Defaults to None.

None

Returns:

Type Description

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

mosaic_info(url, titiler_endpoint=None, **kwargs)

Get the info of a MosaicJSON.

Parameters:

Name Type Description Default
url str

HTTP URL to a MosaicJSON.

required
titiler_endpoint str

TiTiler endpoint, e.g., "https://titiler.opengeos.org". Defaults to None.

None

Returns:

Type Description

A dictionary containing bounds, center, minzoom, maxzoom, and name as keys.

mosaic_info_geojson(url, titiler_endpoint=None, **kwargs)

Get the info of a MosaicJSON.

Parameters:

Name Type Description Default
url str

HTTP URL to a MosaicJSON.

required
titiler_endpoint str

TiTiler endpoint, e.g., "https://titiler.opengeos.org". Defaults to None.

None

Returns:

Type Description

A dictionary representing a dict of GeoJSON.

mosaic_opera(DS, merge_args={})

Mosaics a list of OPERA product granules into a single image (in memory).

Parameters:

Name Type Description Default
DS list

A list of OPERA product granules opened as xarray.DataArray objects.

required
merge_args dict

A dictionary of arguments to pass to the rioxarray.merge_arrays function. Defaults to {}.

{}

Returns:

Type Description

An xarray.DataArray containing the mosaic of the individual OPERA product granule DataArrays.

A colormap for the mosaic, if in the original OPERA metadata, otherwise None.

The nodata value for the mosaic corresponding to the original OPERA product granule metadata.

mosaic_tile(url, titiler_endpoint=None, **kwargs)

Get the tile URL from a MosaicJSON.

Parameters:

Name Type Description Default
url str

HTTP URL to a MosaicJSON.

required
titiler_endpoint str

TiTiler endpoint, e.g., "https://titiler.opengeos.org". Defaults to None.

None

Returns:

Type Description

The tile URL.

nasa_data_download(granules, out_dir=None, provider=None, threads=8, keywords=None)

Downloads NASA Earthdata granules.

Parameters:

Name Type Description Default
granules List[dict]

The granules to download.

required
out_dir str

The output directory where the granules will be downloaded. Defaults to None (current directory).

None
provider str

The provider of the granules.

None
threads int

The number of threads to use for downloading. Defaults to 8.

8
keywords List[str]

The keywords to filter the granules. Defaults to None.

None

nasa_data_granules_to_gdf(granules, crs='EPSG:4326', output=None, **kwargs)

Converts granules data to a GeoDataFrame.

Parameters:

Name Type Description Default
granules List[dict]

A list of granules.

required
crs str

The coordinate reference system (CRS) of the GeoDataFrame. Defaults to "EPSG:4326".

'EPSG:4326'
output str

The output file path to save the GeoDataFrame as a file. Defaults to None.

None
**kwargs Any

Additional keyword arguments for the gpd.GeoDataFrame.to_file() function.

{}

Returns:

Type Description
Any

The resulting GeoDataFrame.

nasa_data_gui(m, position='topright', opened=True, default_dataset='GEDI_L4A_AGB_Density_V2_1_2056', **kwargs)

Search NASA Earth data interactive

Parameters:

Name Type Description Default
m Map

The leaflet Map object. Defaults to None.

required
position str

The position of the widget. Defaults to "topright".

'topright'
opened bool

Whether to open the widget. Defaults to True.

True
default_dataset str

The default dataset. Defaults to "GEDI_L4A_AGB_Density_V2_1_2056".

'GEDI_L4A_AGB_Density_V2_1_2056'

Returns:

Name Type Description
ipywidgets

The tool GUI widget.

nasa_data_login(strategy='all', persist=True, **kwargs)

Logs in to NASA Earthdata.

Parameters:

Name Type Description Default
strategy str

The authentication method. "all": (default) try all methods until one works "interactive": enter username and password. "netrc": retrieve username and password from ~/.netrc. "environment": retrieve username and password from $EARTHDATA_USERNAME and $EARTHDATA_PASSWORD.

'all'
persist bool

Whether to persist credentials in a .netrc file. Defaults to True.

True
**kwargs Any

Additional keyword arguments for the earthaccess.login() function.

{}

Searches for NASA Earthdata granules.

Parameters:

Name Type Description Default
count int

The number of granules to retrieve. Defaults to -1 (retrieve all).

-1
short_name str

The short name of the dataset.

None
bbox List[float]

The bounding box coordinates [xmin, ymin, xmax, ymax].

None
temporal str

The temporal extent of the data.

None
version str

The version of the dataset.

None
doi str

The Digital Object Identifier (DOI) of the dataset.

None
daac str

The Distributed Active Archive Center (DAAC) of the dataset.

None
provider str

The provider of the dataset.

None
output str

The output file path to save the GeoDataFrame as a file.

None
crs str

The coordinate reference system (CRS) of the GeoDataFrame. Defaults to "EPSG:4326".

'EPSG:4326'
return_gdf bool

Whether to return the GeoDataFrame in addition to the granules. Defaults to False.

False
**kwargs Any

Additional keyword arguments for the earthaccess.search_data() function.

{}

Returns:

Type Description
Union[List[dict], tuple]

Union[List[dict], tuple]: The retrieved granules. If return_gdf is True, also returns the resulting GeoDataFrame.

nasa_datasets(keyword=None, df=None, return_short_name=False)

Searches for NASA datasets based on a keyword in a DataFrame.

Parameters:

Name Type Description Default
keyword str

The keyword to search for. Defaults to None.

None
df DataFrame

The DataFrame to search in. If None, it will download the NASA dataset CSV from GitHub. Defaults to None.

None
return_short_name bool

If True, only returns the list of short names of the matched datasets. Defaults to False.

False

Returns:

Type Description

Union[pd.DataFrame, List[str]]: Filtered DataFrame if return_short_name is False, otherwise a list of short names.

nasa_opera_gui(m, position='topright', opened=True, default_dataset='OPERA_L3_DSWX-HLS_V1', backend='ipyleaflet', **kwargs)

Search NASA Earth data interactive

Parameters:

Name Type Description Default
m Map

The leaflet Map object. Defaults to None.

required
position str

The position of the widget. Defaults to "topright".

'topright'
opened bool

Whether to open the widget. Defaults to True.

True
default_dataset str

The default dataset. Defaults to "OPERA_L3_DSWX-HLS_V1".

'OPERA_L3_DSWX-HLS_V1'
backend str

The backend to use. Defaults to "ipyleaflet".

'ipyleaflet'

Returns:

Name Type Description
ipywidgets

The tool GUI widget.

netcdf_tile_layer(filename, variables=None, colormap=None, vmin=None, vmax=None, nodata=None, port='default', debug=False, attribution=None, tile_format='ipyleaflet', layer_name='NetCDF layer', return_client=False, shift_lon=True, lat='lat', lon='lon', **kwargs)

Generate an ipyleaflet/folium TileLayer from a netCDF file. If you are using this function in JupyterHub on a remote server (e.g., Binder, Microsoft Planetary Computer), try adding to following two lines to the beginning of the notebook if the raster does not render properly.

1
2
import os
os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = f'{os.environ['JUPYTERHUB_SERVICE_PREFIX'].lstrip('/')}/proxy/{{port}}'

Parameters:

Name Type Description Default
filename str

File path or HTTP URL to the netCDF file.

required
variables int

The variable/band names to extract data from the netCDF file. Defaults to None. If None, all variables will be extracted.

None
port str

The port to use for the server. Defaults to "default".

'default'
colormap str

The name of the colormap from matplotlib to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale.

None
vmin float

The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None.

None
vmax float

The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None.

None
nodata float

The value from the band to use to interpret as not valid data. Defaults to None.

None
debug bool

If True, the server will be started in debug mode. Defaults to False.

False
attribution str

Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None.

None
tile_format str

The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet".

'ipyleaflet'
layer_name str

The layer name to use. Defaults to "NetCDF layer".

'NetCDF layer'
return_client bool

If True, the tile client will be returned. Defaults to False.

False
shift_lon bool

Flag to shift longitude values from [0, 360] to the range [-180, 180]. Defaults to True.

True
lat str

Name of the latitude variable. Defaults to 'lat'.

'lat'
lon str

Name of the longitude variable. Defaults to 'lon'.

'lon'

Returns:

Type Description

An ipyleaflet.TileLayer or folium.TileLayer.

netcdf_to_tif(filename, output=None, variables=None, shift_lon=True, lat='lat', lon='lon', lev='lev', level_index=0, time=0, crs='epsg:4326', return_vars=False, **kwargs)

Convert a netcdf file to a GeoTIFF file.

Parameters:

Name Type Description Default
filename str

Path to the netcdf file.

required
output str

Path to the output GeoTIFF file. Defaults to None. If None, the output file will be the same as the input file with the extension changed to .tif.

None
variables str | list

Name of the variable or a list of variables to extract. Defaults to None. If None, all variables will be extracted.

None
shift_lon bool

Flag to shift longitude values from [0, 360] to the range [-180, 180]. Defaults to True.

True
lat str

Name of the latitude variable. Defaults to 'lat'.

'lat'
lon str

Name of the longitude variable. Defaults to 'lon'.

'lon'
lev str

Name of the level variable. Defaults to 'lev'.

'lev'
level_index int

Index of the level dimension. Defaults to 0'.

0
time int

Index of the time dimension. Defaults to 0'.

0
crs str

The coordinate reference system. Defaults to 'epsg:4326'.

'epsg:4326'
return_vars bool

Flag to return all variables. Defaults to False.

False

Raises:

Type Description
ImportError

If the xarray or rioxarray package is not installed.

FileNotFoundError

If the netcdf file is not found.

ValueError

If the variable is not found in the netcdf file.

numpy_to_cog(np_array, out_cog, bounds=None, profile=None, dtype=None, dst_crs=None, coord_crs=None)

Converts a numpy array to a COG file.

Parameters:

Name Type Description Default
np_array array

A numpy array representing an image or an HTTP URL to an image.

required
out_cog str

The output COG file path.

required
bounds tuple

The bounds of the image in the format of (minx, miny, maxx, maxy). Defaults to None.

None
profile str | dict

File path to an existing COG file or a dictionary representing the profile. Defaults to None.

None
dtype str

The data type of the output COG file. Defaults to None.

None
dst_crs str

The coordinate reference system of the output COG file. Defaults to "epsg:4326".

None
coord_crs str

The coordinate reference system of bbox coordinates. Defaults to None.

None

numpy_to_image(np_array, filename, transpose=True, bands=None, size=None, resize_args=None, **kwargs)

Converts a numpy array to an image in the specified format, such as JPG, PNG, TIFF, etc.

Parameters:

Name Type Description Default
np_array ndarray

A numpy array or a path to a raster file.

required
filename str

The output filename.

required
transpose bool

Whether to transpose the array from (bands, rows, cols) to (rows, cols, bands). Defaults to True.

True
bands int | list

The band(s) to use, starting from 0. Defaults to None.

None

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.

oam_search_gui(m, position='topright', opened=True)

Generates a tool GUI template using ipywidgets. Icons can be found at https://fontawesome.com/v4/icons

Parameters:

Name Type Description Default
m Map

The leaflet Map object. Defaults to None.

required

Returns:

Name Type Description
ipywidgets

The tool GUI widget.

open_data_widget(m)

A widget for opening local vector/raster data.

Parameters:

Name Type Description Default
m object

leafmap.Map

required

open_image_from_url(url)

Loads an image from the specified URL.

Parameters:

Name Type Description Default
url str

URL of the image.

required

Returns:

Type Description
Any

An image object.

open_raster_gui(m)

A widget for opening local/remote COG/STAC data.

Parameters:

Name Type Description Default
m object

leafmap.Map

required

overlay_images(image1, image2, alpha=0.5, backend='TkAgg', height_ratios=[10, 1], show_args1={}, show_args2={})

Overlays two images using a slider to control the opacity of the top image.

Parameters:

Name Type Description Default
image1 str | ndarray

The first input image at the bottom represented as a NumPy array or the path to the image.

required
image2 _type_

The second input image on top represented as a NumPy array or the path to the image.

required
alpha float

The alpha value of the top image. Defaults to 0.5.

0.5
backend str

The backend of the matplotlib plot. Defaults to "TkAgg".

'TkAgg'
height_ratios list

The height ratios of the two subplots. Defaults to [10, 1].

[10, 1]
show_args1 dict

The keyword arguments to pass to the imshow() function for the first image. Defaults to {}.

{}
show_args2 dict

The keyword arguments to pass to the imshow() function for the second image. Defaults to {}.

{}

pandas_to_geojson(df, coordinates=['lng', 'lat'], geometry_type='Point', properties=None, output=None)

Convert a DataFrame to a GeoJSON format.

Parameters:

Name Type Description Default
df DataFrame

The input DataFrame containing the data.

required
coordinates list

A list of two column names representing the longitude and latitude coordinates.

['lng', 'lat']
geometry_type str

The type of geometry for the GeoJSON features (e.g., "Point", "LineString", "Polygon").

'Point'
properties list

A list of column names to include in the properties of each GeoJSON feature. If None, all columns except the coordinate columns are included.

None
output str

The file path to save the GeoJSON output. If None, the GeoJSON is not saved to a file.

None

Returns:

Type Description
dict

A dictionary representing the GeoJSON object.

planet_biannual_tiles_tropical(api_key=None, token_name='PLANET_API_KEY', tile_format='ipyleaflet')

Generates Planet bi-annual imagery TileLayer based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf

Parameters:

Name Type Description Default
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'
tile_format str

The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".

'ipyleaflet'

Raises:

Type Description
ValueError

If the tile layer format is invalid.

Returns:

Type Description

A dictionary of TileLayer.

planet_biannual_tropical(api_key=None, token_name='PLANET_API_KEY')

Generates Planet bi-annual imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf

Parameters:

Name Type Description Default
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'

Raises:

Type Description
ValueError

If the API key could not be found.

Returns:

Type Description
List[str]

A list of tile URLs.

planet_by_month(year=2016, month=1, api_key=None, token_name='PLANET_API_KEY')

Gets Planet global mosaic tile url by month. To get a Planet API key, see https://developers.planet.com/quickstart/apis/

Parameters:

Name Type Description Default
year int

The year of Planet global mosaic, must be >=2016. Defaults to 2016.

2016
month int

The month of Planet global mosaic, must be 1-12. Defaults to 1.

1
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'

Raises:

Type Description
ValueError

The Planet API key is not provided.

ValueError

The year is invalid.

ValueError

The month is invalid.

ValueError

The month is invalid.

Returns:

Type Description

A Planet global mosaic tile URL.

planet_by_quarter(year=2016, quarter=1, api_key=None, token_name='PLANET_API_KEY')

Gets Planet global mosaic tile url by quarter. To get a Planet API key, see https://developers.planet.com/quickstart/apis/

Parameters:

Name Type Description Default
year int

The year of Planet global mosaic, must be >=2016. Defaults to 2016.

2016
quarter int

The quarter of Planet global mosaic, must be 1-4. Defaults to 1.

1
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'

Raises:

Type Description
ValueError

The Planet API key is not provided.

ValueError

The year is invalid.

ValueError

The quarter is invalid.

ValueError

The quarter is invalid.

Returns:

Type Description

A Planet global mosaic tile URL.

planet_catalog(api_key=None, token_name='PLANET_API_KEY')

Generates Planet bi-annual and monthly imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf

Parameters:

Name Type Description Default
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'

Returns:

Name Type Description
list List[str]

A list of tile URLs.

planet_catalog_tropical(api_key=None, token_name='PLANET_API_KEY')

Generates Planet bi-annual and monthly imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf

Parameters:

Name Type Description Default
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'

Returns:

Name Type Description
list List[str]

A list of tile URLs.

planet_monthly(api_key=None, token_name='PLANET_API_KEY')

Generates Planet monthly imagery URLs based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/

Parameters:

Name Type Description Default
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'

Raises:

Type Description
ValueError

If the API key could not be found.

Returns:

Name Type Description
list List[str]

A list of tile URLs.

planet_monthly_tiles(api_key=None, token_name='PLANET_API_KEY', tile_format='ipyleaflet')

Generates Planet monthly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/

Parameters:

Name Type Description Default
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'
tile_format str

The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".

'ipyleaflet'

Raises:

Type Description
ValueError

If the tile layer format is invalid.

Returns:

Name Type Description
dict Dict[str, Any]

A dictionary of TileLayer.

planet_monthly_tiles_tropical(api_key=None, token_name='PLANET_API_KEY', tile_format='ipyleaflet')

Generates Planet monthly imagery TileLayer based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf

Parameters:

Name Type Description Default
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'
tile_format str

The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".

'ipyleaflet'

Raises:

Type Description
ValueError

If the tile layer format is invalid.

Returns:

Type Description

A dictionary of TileLayer.

planet_monthly_tropical(api_key=None, token_name='PLANET_API_KEY')

Generates Planet monthly imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf

Parameters:

Name Type Description Default
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'

Raises:

Type Description
ValueError

If the API key could not be found.

Returns:

Type Description
List[str]

A list of tile URLs.

planet_quarterly(api_key=None, token_name='PLANET_API_KEY')

Generates Planet quarterly imagery URLs based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/

Parameters:

Name Type Description Default
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'

Raises:

Type Description
ValueError

If the API key could not be found.

Returns:

Name Type Description
list List[str]

A list of tile URLs.

planet_quarterly_tiles(api_key=None, token_name='PLANET_API_KEY', tile_format='ipyleaflet')

Generates Planet quarterly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/

Parameters:

Name Type Description Default
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'
tile_format str

The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".

'ipyleaflet'

Raises:

Type Description
ValueError

If the tile layer format is invalid.

Returns:

Name Type Description
dict

A dictionary of TileLayer.

planet_tile_by_month(year=2016, month=1, name=None, api_key=None, token_name='PLANET_API_KEY', tile_format='ipyleaflet')

Generates Planet monthly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis

Parameters:

Name Type Description Default
year int

The year of Planet global mosaic, must be >=2016. Defaults to 2016.

2016
month int

The month of Planet global mosaic, must be 1-12. Defaults to 1.

1
name str

The layer name to use. Defaults to None.

None
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'
tile_format str

The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".

'ipyleaflet'

Raises:

Type Description
ValueError

If the tile layer format is invalid.

Returns:

Name Type Description
dict

A dictionary of TileLayer.

planet_tile_by_quarter(year=2016, quarter=1, name=None, api_key=None, token_name='PLANET_API_KEY', tile_format='ipyleaflet')

Generates Planet quarterly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis

Parameters:

Name Type Description Default
year int

The year of Planet global mosaic, must be >=2016. Defaults to 2016.

2016
quarter int

The quarter of Planet global mosaic, must be 1-4. Defaults to 1.

1
name str

The layer name to use. Defaults to None.

None
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'
tile_format str

The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".

'ipyleaflet'

Raises:

Type Description
ValueError

If the tile layer format is invalid.

Returns:

Name Type Description
dict

A dictionary of TileLayer.

planet_tiles(api_key=None, token_name='PLANET_API_KEY', tile_format='ipyleaflet')

Generates Planet imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/

Parameters:

Name Type Description Default
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'
tile_format str

The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".

'ipyleaflet'

Raises:

Type Description
ValueError

If the tile layer format is invalid.

Returns:

Name Type Description
dict

A dictionary of TileLayer.

planet_tiles_tropical(api_key=None, token_name='PLANET_API_KEY', tile_format='ipyleaflet')

Generates Planet monthly imagery TileLayer based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf

Parameters:

Name Type Description Default
api_key str

The Planet API key. Defaults to None.

None
token_name str

The environment variable name of the API key. Defaults to "PLANET_API_KEY".

'PLANET_API_KEY'
tile_format str

The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".

'ipyleaflet'

Raises:

Type Description
ValueError

If the tile layer format is invalid.

Returns:

Name Type Description
dict Dict[str, Any]

A dictionary of TileLayer.

plot_actual_vs_predicted(df, x_col='y', y_col='y_pred', xlim=None, ylim=None, title='Actual vs. Predicted Values', x_label='Actual Values', y_label='Predicted Values', marker_size=6, marker_opacity=0.7, marker_color='blue', line_color='red', line_dash='dash', width=800, height=800, showlegend=True, template='plotly_white', square_aspect=True, return_figure=False, **kwargs)

Plots a customizable scatter plot with a reference line for actual vs. predicted values.

Parameters:

Name Type Description Default
df DataFrame

A pandas DataFrame with columns for actual and predicted values.

required
x_col str

Column name for the x-axis (actual values).

'y'
y_col str

Column name for the y-axis (predicted values).

'y_pred'
xlim tuple

A tuple (min, max) for x-axis limits.

None
ylim tuple

A tuple (min, max) for y-axis limits.

None
title str

Title of the plot.

'Actual vs. Predicted Values'
x_label str

Label for the x-axis.

'Actual Values'
y_label str

Label for the y-axis.

'Predicted Values'
marker_size int

Size of the scatter plot markers.

6
marker_opacity float

Opacity of the scatter plot markers.

0.7
marker_color str

Color of the scatter plot markers.

'blue'
line_color str

Color of the reference line.

'red'
line_dash str

Dash style of the reference line ('dash', 'dot', etc.).

'dash'
width int

Width of the plot in pixels.

800
height int

Height of the plot in pixels.

800
showlegend bool

Whether to show the legend.

True
template str

Plotly template for styling.

'plotly_white'
square_aspect bool

Whether to enforce a square aspect ratio.

True
return_figure bool

Whether to return the Plotly figure object.

False
**kwargs Any

Additional keyword arguments for Plotly figure.

{}

Returns:

Type Description

A Plotly figure object.

plot_raster(image, band=None, cmap='terrain', proj='EPSG:3857', figsize=None, open_kwargs={}, **kwargs)

Plot a raster image.

Parameters:

Name Type Description Default
image str | DataArray

The input raster image, can be a file path, HTTP URL, or xarray.DataArray.

required
band int

The band index, starting from zero. Defaults to None.

None
cmap str

The matplotlib colormap to use. Defaults to "terrain".

'terrain'
proj str

The EPSG projection code. Defaults to "EPSG:3857".

'EPSG:3857'
figsize tuple

The figure size as a tuple, such as (10, 8). Defaults to None.

None
open_kwargs dict

The keyword arguments to pass to rioxarray.open_rasterio. Defaults to {}.

{}
**kwargs Any

Additional keyword arguments to pass to xarray.DataArray.plot().

{}

plot_raster_3d(image, band=None, cmap='terrain', factor=1.0, proj='EPSG:3857', background=None, x=None, y=None, z=None, order=None, component=None, open_kwargs={}, mesh_kwargs={}, **kwargs)

Plot a raster image in 3D.

Parameters:

Name Type Description Default
image str | DataArray

The input raster image, can be a file path, HTTP URL, or xarray.DataArray.

required
band int

The band index, starting from zero. Defaults to None.

None
cmap str

The matplotlib colormap to use. Defaults to "terrain".

'terrain'
factor float

The scaling factor for the raster. Defaults to 1.0.

1.0
proj str

The EPSG projection code. Defaults to "EPSG:3857".

'EPSG:3857'
background str

The background color. Defaults to None.

None
x str

The x coordinate. Defaults to None.

None
y str

The y coordinate. Defaults to None.

None
z str

The z coordinate. Defaults to None.

None
order str

The order of the coordinates. Defaults to None.

None
component str

The component of the coordinates. Defaults to None.

None
open_kwargs dict

The keyword arguments to pass to rioxarray.open_rasterio. Defaults to {}.

{}
mesh_kwargs dict

The keyword arguments to pass to pyvista.mesh.warp_by_scalar(). Defaults to {}.

{}
**kwargs Any

Additional keyword arguments to pass to xarray.DataArray.plot().

{}

plotly_basemap_gui(canvas, map_min_width='78%', map_max_width='98%')

Widget for changing basemaps.

Parameters:

Name Type Description Default
m object

leafmap.Map.

required

plotly_search_basemaps(canvas)

The widget for search XYZ tile services.

Parameters:

Name Type Description Default
m Map

The Plotly Map object. Defaults to None.

required

Returns:

Name Type Description
ipywidgets

The tool GUI widget.

plotly_toolbar(canvas)

Creates the main toolbar and adds it to the map.

Parameters:

Name Type Description Default
m Map

The plotly Map object.

required

plotly_whitebox_gui(canvas)

Display a GUI for the whitebox tool.

Parameters:

Name Type Description Default
canvas Canvas

Map canvas.

required

pmtiles_header(input_file)

Fetch the header information from a local or remote .pmtiles file.

This function retrieves the header from a PMTiles file, either local or hosted remotely. It deserializes the header and calculates the center and bounds of the tiles from the given metadata in the header.

Parameters:

Name Type Description Default
input_file str

Path to the .pmtiles file, or its URL if the file is hosted remotely.

required

Returns:

Type Description

A dictionary containing the header information, including center and bounds.

Raises:

Type Description
ImportError

If the pmtiles library is not installed.

ValueError

If the input file is not a .pmtiles file or if it does not exist.

Example

header = pmtiles_header("https://example.com/path/to/tiles.pmtiles") print(header["center"]) [52.5200, 13.4050]

Note

If fetching a remote PMTiles file, this function only downloads the first 127 bytes of the file to retrieve the header.

pmtiles_metadata(input_file)

Fetch the metadata from a local or remote .pmtiles file.

This function retrieves metadata from a PMTiles file, whether it's local or hosted remotely. If it's remote, the function fetches the header to determine the range of bytes to download for obtaining the metadata. It then reads the metadata and extracts the layer names.

Parameters:

Name Type Description Default
input_file str

Path to the .pmtiles file, or its URL if the file is hosted remotely.

required

Returns:

Type Description
Dict[str, Union[str, int, List[str]]]

A dictionary containing the metadata information, including layer names.

Raises:

Type Description
ImportError

If the pmtiles library is not installed.

ValueError

If the input file is not a .pmtiles file or if it does not exist.

Example

metadata = pmtiles_metadata("https://example.com/path/to/tiles.pmtiles") print(metadata["layer_names"]) ['buildings', 'roads']

Note

If fetching a remote PMTiles file, this function may perform multiple requests to minimize the amount of data downloaded.

pmtiles_style(url, layers=None, cmap='Set3', n_class=None, opacity=0.5, circle_radius=5, line_width=1, attribution='PMTiles', **kwargs)

Generates a Mapbox style JSON for rendering PMTiles data.

Parameters:

Name Type Description Default
url str

The URL of the PMTiles file.

required
layers str or list[str]

The layers to include in the style. If None, all layers will be included. Defaults to None.

None
cmap str

The color map to use for styling the layers. Defaults to "Set3".

'Set3'
n_class int

The number of classes to use for styling. If None, the number of classes will be determined automatically based on the color map. Defaults to None.

None
opacity float

The fill opacity for polygon layers. Defaults to 0.5.

0.5
circle_radius int

The circle radius for point layers. Defaults to 5.

5
line_width int

The line width for line layers. Defaults to 1.

1
attribution str

The attribution text for the data source. Defaults to "PMTiles".

'PMTiles'

Returns:

Type Description

The Mapbox style JSON.

Raises:

Type Description
ValueError

If the layers argument is not a string or a list.

ValueError

If a layer specified in the layers argument does not exist in the PMTiles file.

png_to_gif(in_dir, out_gif, fps=10, loop=0)

Convert a list of png images to gif.

Parameters:

Name Type Description Default
in_dir str

The input directory containing png images.

required
out_gif str

The output file path to the gif.

required
fps int

Frames per second. Defaults to 10.

10
loop bool

controls how many times the animation repeats. 1 means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0.

0

Raises:

Type Description
FileNotFoundError

No png images could be found.

point_to_gdf(x, y, point_crs='EPSG:4326', to_crs='EPSG:4326', **kwargs)

Convert a point to a GeoDataFrame.

Parameters:

Name Type Description Default
x float

X coordinate of the point.

required
y float

Y coordinate of the point.

required
point_crs str

Coordinate Reference System of the point.

'EPSG:4326'

Returns:

Type Description

A GeoDataFrame containing the point.

points_from_xy(data, x=None, y=None, z=None, crs=None, **kwargs)

Create a GeoPandas GeoDataFrame from a csv or Pandas DataFrame containing x, y, z values.

Parameters:

Name Type Description Default
data str | DataFrame

A csv or Pandas DataFrame containing x, y, z values.

required
x str

The column name for the x values. Defaults to "longitude".

None
y str

The column name for the y values. Defaults to "latitude".

None
z str

The column name for the z values. Defaults to None.

None
crs str | int

The coordinate reference system for the GeoDataFrame. Defaults to None.

None

Returns:

Type Description

A GeoPandas GeoDataFrame containing x, y, z values.

points_to_line(data, src_lat, src_lon, dst_lat, dst_lon, crs='EPSG:4326', **kwargs)

Converts source and destination coordinates into a GeoDataFrame with LineString geometries.

Parameters:

Name Type Description Default
data Union[str, DataFrame, GeoDataFrame]

Input data which can be a file path or a DataFrame.

required
src_lat str

Column name for source latitude.

required
src_lon str

Column name for source longitude.

required
dst_lat str

Column name for destination latitude.

required
dst_lon str

Column name for destination longitude.

required
crs str

Coordinate reference system. Defaults to "EPSG:4326".

'EPSG:4326'
**kwargs Any

Additional arguments passed to the file reading functions.

{}

Returns:

Type Description
GeoDataFrame

A GeoDataFrame with LineString geometries.

random_string(string_length=3)

Generates a random string of fixed length.

Parameters:

Name Type Description Default
string_length int

Fixed length. Defaults to 3.

3

Returns:

Type Description
str

A random string.

raster_to_vector(source, output, simplify_tolerance=None, dst_crs=None, open_args={}, **kwargs)

Vectorize a raster dataset.

Parameters:

Name Type Description Default
source str

The path to the tiff file.

required
output str

The path to the vector file.

required
simplify_tolerance float

The maximum allowed geometry displacement. The higher this value, the smaller the number of vertices in the resulting geometry.

None

read_file(data, **kwargs)

Reads a file and returns a DataFrame or GeoDataFrame.

Parameters:

Name Type Description Default
data str

The file path or a DataFrame/GeoDataFrame.

required
**kwargs Any

Additional arguments passed to the file reading function.

{}

Returns:

Type Description
Union[DataFrame, GeoDataFrame]

Union[pd.DataFrame, gpd.GeoDataFrame]: The read data as a DataFrame or GeoDataFrame.

Raises:

Type Description
ValueError

If the data type is unsupported.

read_file_from_url(url, return_type='list', encoding='utf-8')

Reads a file from a URL.

Parameters:

Name Type Description Default
url str

The URL of the file.

required
return_type str

The return type, can either be string or list. Defaults to "list".

'list'
encoding str

The encoding of the file. Defaults to "utf-8".

'utf-8'

Raises:

Type Description
ValueError

The return type must be either list or string.

Returns:

Type Description

The contents of the file as a list or string depending on return_type.

read_geojson(data, **kwargs)

Fetches and parses a GeoJSON file from a given URL.

Parameters:

Name Type Description Default
data str

The URL of the GeoJSON file.

required
**kwargs Any

Additional keyword arguments to pass to the requests.get() method.

{}

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The parsed GeoJSON data.

read_lidar(filename, **kwargs)

Read a LAS file.

Parameters:

Name Type Description Default
filename str

A local file path or HTTP URL to a LAS file.

required

Returns:

Type Description

The LasData object returned by laspy.read.

read_netcdf(filename, **kwargs)

Read a netcdf file.

Parameters:

Name Type Description Default
filename str

File path or HTTP URL to the netcdf file.

required

Raises:

Type Description
ImportError

If the xarray or rioxarray package is not installed.

FileNotFoundError

If the netcdf file is not found.

Returns:

Type Description

The netcdf file as an xarray dataset.

read_parquet(source, geometry=None, columns=None, exclude=None, db=None, table_name=None, sql=None, limit=None, src_crs=None, dst_crs=None, return_type='gdf', **kwargs)

Read Parquet data from a source and return a GeoDataFrame or DataFrame.

Parameters:

Name Type Description Default
source str

The path to the Parquet file or directory containing Parquet files.

required
geometry str

The name of the geometry column. Defaults to None.

None
columns str or list

The columns to select. Defaults to None (select all columns).

None
exclude str or list

The columns to exclude from the selection. Defaults to None.

None
db str

The DuckDB database path or alias. Defaults to None.

None
table_name str

The name of the table in the DuckDB database. Defaults to None.

None
sql str

The SQL query to execute. Defaults to None.

None
limit int

The maximum number of rows to return. Defaults to None (return all rows).

None
src_crs str

The source CRS (Coordinate Reference System) of the geometries. Defaults to None.

None
dst_crs str

The target CRS to reproject the geometries. Defaults to None.

None
return_type str

The type of object to return: - 'gdf': GeoDataFrame (default) - 'df': DataFrame - 'numpy': NumPy array - 'arrow': Arrow Table - 'polars': Polars DataFrame

'gdf'
**kwargs Any

Additional keyword arguments that are passed to the DuckDB connection.

{}

Returns:

Type Description

Union[gpd.GeoDataFrame, pd.DataFrame, np.ndarray]: The loaded data.

Raises:

Type Description
ValueError

If the columns or exclude arguments are not of the correct type.

read_postgis(sql, con, geom_col='geom', crs=None, **kwargs)

Reads data from a PostGIS database and returns a GeoDataFrame.

Parameters:

Name Type Description Default
sql str

SQL query to execute in selecting entries from database, or name of the table to read from the database.

required
con Engine

Active connection to the database to query.

required
geom_col str

Column name to convert to shapely geometries. Defaults to "geom".

'geom'
crs str | dict

CRS to use for the returned GeoDataFrame; if not set, tries to determine CRS from the SRID associated with the first geometry in the database, and assigns that to all geometries. Defaults to None.

None

Returns:

Type Description
Any

read_raster(source, window=None, return_array=True, coord_crs=None, request_payer='bucket-owner', env_args={}, open_args={}, **kwargs)

Read a raster from S3.

Parameters:

Name Type Description Default
source str

The path to the raster on S3.

required
window tuple

The window (col_off, row_off, width, height) to read. Defaults to None.

None
return_array bool

Whether to return a numpy array. Defaults to True.

True
coord_crs str

The coordinate CRS of the input coordinates. Defaults to None.

None
request_payer str

Specifies who pays for the download from S3. Can be "bucket-owner" or "requester". Defaults to "bucket-owner".

'bucket-owner'
env_args dict

Additional arguments to pass to rasterio.Env(). Defaults to {}.

{}
open_args dict

Additional arguments to pass to rasterio.open(). Defaults to {}.

{}

Returns:

Type Description

The raster as a numpy array.

read_rasters(sources, window=None, coord_crs=None, request_payer='bucket-owner', env_args={}, open_args={}, **kwargs)

Read a raster from S3.

Parameters:

Name Type Description Default
sources str

The list of paths to the raster files.

required
window tuple

The window (col_off, row_off, width, height) to read. Defaults to None.

None
coord_crs str

The coordinate CRS of the input coordinates. Defaults to None.

None
request_payer str

Specifies who pays for the download from S3. Can be "bucket-owner" or "requester". Defaults to "bucket-owner".

'bucket-owner'
env_args dict

Additional arguments to pass to rasterio.Env(). Defaults to {}.

{}
open_args dict

Additional arguments to pass to rasterio.open(). Defaults to {}.

{}

Returns:

Type Description

The raster as a numpy array.

read_vector(source, layer=None, **kwargs)

Reads vector data from various formats including GeoParquet.

This function dynamically determines the file type based on extension and reads it into a GeoDataFrame. It supports both local files and HTTP/HTTPS URLs.

Parameters:

Name Type Description Default
source str

Path to the vector file or URL.

required
layer str | int

String or integer specifying which layer to read from multi-layer files (only applicable for formats like GPKG, GeoJSON, etc.). Defaults to None.

None
**kwargs Any

Additional keyword arguments to pass to the underlying reader.

{}

Returns:

Type Description

A GeoDataFrame containing the vector data.

Raises:

Type Description
ValueError

If the file format is not supported or source cannot be accessed.

Examples:

Read a local shapefile

1
2
3
4
5
6
7
>>> gdf = read_vector("path/to/data.shp")
>>>
Read a GeoParquet file from URL
>>> gdf = read_vector("https://example.com/data.parquet")
>>>
Read a specific layer from a GeoPackage
>>> gdf = read_vector("path/to/data.gpkg", layer="layer_name")

reduce_gif_size(in_gif, out_gif=None)

Reduces a GIF image using ffmpeg.

Parameters:

Name Type Description Default
in_gif str

The input file path to the GIF image.

required
out_gif str

The output file path to the GIF image. Defaults to None.

None

regularize(source, output=None, crs='EPSG:4326', **kwargs)

Regularize a polygon GeoDataFrame.

Parameters:

Name Type Description Default
source str | GeoDataFrame

The input file path or a GeoDataFrame.

required
output str

The output file path. Defaults to None.

None

Returns:

Type Description

The output GeoDataFrame.

remove_port_from_string(data)

Removes the port number from all URLs in the given string.

Args:: data (str): The input string containing URLs.

Returns:

Type Description
str

The string with port numbers removed from all URLs.

replace_hyphens_in_keys(d)

Recursively replaces hyphens with underscores in dictionary keys.

Parameters:

Name Type Description Default
d Union[Dict, List, Any]

The input dictionary, list or any other data type.

required

Returns:

Type Description
Union[Dict, List, Any]

Union[Dict, List, Any]: The modified dictionary or list with keys having hyphens replaced with underscores,

Union[Dict, List, Any]

or the original input if it's not a dictionary or list.

replace_top_level_hyphens(d)

Replaces hyphens with underscores in top-level dictionary keys.

Parameters:

Name Type Description Default
d Union[Dict, Any]

The input dictionary or any other data type.

required

Returns:

Type Description
Union[Dict, Any]

Union[Dict, Any]: The modified dictionary with top-level keys having hyphens replaced with underscores,

Union[Dict, Any]

or the original input if it's not a dictionary.

replace_underscores_in_keys(d)

Recursively replaces underscores with hyphens in dictionary keys.

Parameters:

Name Type Description Default
d Union[Dict, List, Any]

The input dictionary, list or any other data type.

required

Returns:

Type Description
Union[Dict, List, Any]

Union[Dict, List, Any]: The modified dictionary or list with keys having underscores replaced with hyphens,

Union[Dict, List, Any]

or the original input if it's not a dictionary or list.

reproject(image, output, dst_crs='EPSG:4326', resampling='nearest', to_cog=True, **kwargs)

Reprojects an image.

Parameters:

Name Type Description Default
image str

The input image filepath.

required
output str

The output image filepath.

required
dst_crs str

The destination CRS. Defaults to "EPSG:4326".

'EPSG:4326'
resampling Resampling

The resampling method. Defaults to "nearest".

'nearest'
to_cog bool

Whether to convert the output image to a Cloud Optimized GeoTIFF. Defaults to True.

True
**kwargs Any

Additional keyword arguments to pass to rasterio.open.

{}

rgb_to_hex(rgb=(255, 255, 255))

Converts RGB to hex color. In RGB color R stands for Red, G stands for Green, and B stands for Blue, and it ranges from the decimal value of 0 – 255.

Parameters:

Name Type Description Default
rgb tuple

RGB color code as a tuple of (red, green, blue). Defaults to (255, 255, 255).

(255, 255, 255)

Returns:

Type Description
str

A hex color code.

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)

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)

s3_credential_provider(**kwargs)

Create a Boto3 credential provider for S3 authentication.

This function creates a Boto3 credential provider that can be used with obstore for S3 authentication. It uses the default AWS credential chain (environment variables, AWS config files, IAM roles, etc.).

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments to pass to the Boto3CredentialProvider. Common options include: - profile_name (str): AWS profile name to use - region_name (str): AWS region name

{}

Returns:

Name Type Description
Boto3CredentialProvider Boto3CredentialProvider

A credential provider instance that can be used with obstore S3Store for authentication.

Example

provider = s3_credential_provider(profile_name='my-profile') store = S3Store('my-bucket', credential_provider=provider)

s3_download_file(filename=None, bucket=None, key=None, outfile=None, **kwargs)

Download a file from S3.

Parameters:

Name Type Description Default
filename str

The full path to the file. Defaults to None.

None
bucket str

The name of the bucket. Defaults to None.

None
key str

The key of the file. Defaults to None.

None
outfile str

The name of the output file. Defaults to None.

None

s3_download_files(filenames=None, bucket=None, keys=None, outdir=None, quiet=False, **kwargs)

Download multiple files from S3.

Parameters:

Name Type Description Default
filenames list

A list of filenames. Defaults to None.

None
bucket str

The name of the bucket. Defaults to None.

None
keys list

A list of keys. Defaults to None.

None
outdir str

The name of the output directory. Defaults to None.

None
quiet bool

Suppress output. Defaults to False.

False

Raises:

Type Description
ValueError

If neither filenames or keys are provided.

s3_get_file(path, region=None, config=None, client_options=None, retry_config=None, credential_provider=None, skip_signature=True, output_file=None, overwrite=False)

Download a file from S3 to local filesystem.

This function downloads a single file from an S3 bucket using the obstore library. It supports both full S3 URLs and relative paths, and can save the file to a specified location or the system's temporary directory.

Parameters:

Name Type Description Default
path str

The S3 path to the file. Can be either: - Full S3 URL: 's3://bucket/path/to/file.ext' - Relative path: 'bucket/path/to/file.ext' (s3:// will be added)

required
region str

AWS region where the bucket is located. If not provided, uses default region.

None
config dict

Additional S3 configuration options.

None
client_options dict

Additional S3 client options.

None
retry_config dict

Retry configuration for S3 operations.

None
credential_provider Boto3CredentialProvider

Custom credential provider. If not provided, creates a default one.

None
skip_signature bool

Whether to skip request signing for public buckets. Defaults to True.

True
output_file str

Local path where the file should be saved. If not provided, saves to system temp directory with the original filename.

None
overwrite bool

Whether to overwrite the file if it already exists. Defaults to False.

False

Returns:

Type Description
str

The local path where the file was saved.

Raises:

Type Description
FileNotFoundError

If the file does not exist in the S3 bucket.

PermissionError

If there are insufficient permissions to write to the output location.

ValueError

If the path format is invalid.

Example

Download to temp directory

local_path = s3_get_file( ... 's3://my-bucket/data/file.parquet', ... region='us-west-2' ... )

Download to specific location

local_path = s3_get_file( ... 's3://my-bucket/data/file.parquet', ... region='us-west-2', ... output_file='/home/user/downloads/file.parquet' ... )

print(f"File downloaded to: {local_path}")

s3_get_object(bucket, key, output=None, chunk_size=1024 * 1024, request_payer='bucket-owner', quiet=False, client_args={}, **kwargs)

Download a file from S3.

Parameters:

Name Type Description Default
bucket str

The name of the bucket.

required
key key

The key of the file.

required
output str

The name of the output file. Defaults to None.

None
chunk_size int

The chunk size in bytes. Defaults to 1024 * 1024.

1024 * 1024
request_payer str

Specifies who pays for the download from S3.

'bucket-owner'
quiet bool

Suppress output. Defaults to False. Can be "bucket-owner" or "requester". Defaults to "bucket-owner".

False
client_args dict

Additional arguments to pass to boto3.client(). Defaults to {}.

{}
**kwargs Any

Additional arguments to pass to boto3.client().get_object().

{}

s3_get_objects(bucket, keys=None, out_dir=None, prefix=None, limit=None, ext=None, chunk_size=1024 * 1024, request_payer='bucket-owner', quiet=True, client_args={}, **kwargs)

Download multiple files from S3.

Parameters:

Name Type Description Default
bucket str

The name of the bucket.

required
keys list

A list of keys. Defaults to None.

None
out_dir str

The name of the output directory. Defaults to None.

None
prefix str

Limits the response to keys that begin with the specified prefix. Defaults to None.

None
limit int

The maximum number of keys returned in the response body.

None
ext str

Filter by file extension. Defaults to None.

None
chunk_size int

The chunk size in bytes. Defaults to 1024 * 1024.

1024 * 1024
request_payer str

Specifies who pays for the download from S3. Can be "bucket-owner" or "requester". Defaults to "bucket-owner".

'bucket-owner'
quiet bool

Suppress output. Defaults to True.

True
client_args dict

Additional arguments to pass to boto3.client(). Defaults to {}.

{}
**kwargs Any

Additional arguments to pass to boto3.client().get_object().

{}

s3_list_directories(bucket=None, prefix=None, path=None, region=None, config=None, client_options=None, retry_config=None, credential_provider=None, skip_signature=True, return_full_path=False)

List directories (common prefixes) in an S3 bucket.

This function lists directories (common prefixes) in an S3 bucket using the obstore library. It can work with either bucket/prefix parameters or a full S3 path.

Parameters:

Name Type Description Default
bucket str

The S3 bucket name. Required if path is not provided.

None
prefix str

The prefix to filter directories. Required if path is not provided.

None
path str

Full S3 path in format 's3://bucket/prefix'. If provided, bucket and prefix are extracted from this.

None
region str

AWS region where the bucket is located. If not provided, uses default region.

None
config dict

Additional S3 configuration options.

None
client_options dict

Additional S3 client options.

None
retry_config dict

Retry configuration for S3 operations.

None
credential_provider Boto3CredentialProvider

Custom credential provider. If not provided, creates a default one.

None
skip_signature bool

Whether to skip request signing for public buckets. Defaults to True.

True
return_full_path bool

Whether to return full S3 paths or just directory names. Defaults to False.

False

Returns:

Type Description
List[str]

List of directory names or full S3 paths, depending on return_full_path parameter.

Raises:

Type Description
ValueError

If neither path nor both bucket and prefix are provided.

Example

Using bucket and prefix

dirs = s3_list_directories( ... bucket='my-bucket', ... prefix='data/', ... region='us-west-2' ... )

Using full S3 path

dirs = s3_list_directories( ... path='s3://my-bucket/data/', ... region='us-west-2', ... return_full_path=True ... )

s3_list_files(bucket=None, prefix=None, path=None, file_ext=None, region=None, config=None, client_options=None, retry_config=None, credential_provider=None, skip_signature=True, return_full_path=False)

List files in an S3 bucket with optional filtering.

This function lists files in an S3 bucket using the obstore library. It supports filtering by file extension and can return either relative paths or full S3 URLs.

Parameters:

Name Type Description Default
bucket str

The S3 bucket name. Required if path is not provided.

None
prefix str

The prefix to filter files. Required if path is not provided.

None
path str

Full S3 path in format 's3://bucket/prefix'. If provided, bucket and prefix are extracted from this.

None
file_ext str

File extension to filter by (e.g., '.parquet', '.json'). If provided, only files with this extension are returned.

None
region str

AWS region where the bucket is located. If not provided, uses default region.

None
config dict

Additional S3 configuration options.

None
client_options dict

Additional S3 client options.

None
retry_config dict

Retry configuration for S3 operations.

None
credential_provider Boto3CredentialProvider

Custom credential provider. If not provided, creates a default one.

None
skip_signature bool

Whether to skip request signing for public buckets. Defaults to True.

True
return_full_path bool

Whether to return full S3 URLs or relative paths. Defaults to False.

False

Returns:

Type Description
List[str]

List of file paths. Format depends on return_full_path parameter: - If True: Full S3 URLs like 's3://bucket/path/file.ext' - If False: Relative paths like 'path/file.ext'

Raises:

Type Description
ValueError

If neither path nor both bucket and prefix are provided.

Example

List all files in a directory

files = s3_list_files( ... bucket='my-bucket', ... prefix='data/2024/', ... region='us-west-2' ... )

List only parquet files with full paths

parquet_files = s3_list_files( ... path='s3://my-bucket/data/2024/', ... file_ext='.parquet', ... return_full_path=True ... )

s3_list_objects(bucket, prefix=None, limit=None, ext=None, fullpath=True, request_payer='bucket-owner', client_args={}, **kwargs)

List objects in a S3 bucket

Parameters:

Name Type Description Default
bucket str

The name of the bucket.

required
prefix str

Limits the response to keys that begin with the specified prefix. Defaults to None.

None
limit init

The maximum number of keys returned in the response body.

None
ext str

Filter by file extension. Defaults to None.

None
fullpath bool

Return full path. Defaults to True.

True
request_payer str

Specifies who pays for the download from S3. Can be "bucket-owner" or "requester". Defaults to "bucket-owner".

'bucket-owner'
client_args dict

Additional arguments to pass to boto3.client(). Defaults to {}.

{}

Returns:

Type Description

List of objects.

s3_to_https(s3_url, region='af-south-1')

Convert an S3 URI to an HTTPS URL for public access.

Parameters:

Name Type Description Default
s3_url str

The S3 URI, e.g., "s3://bucket-name/path/to/file.tif"

required
region str

The AWS region where the bucket is located.

'af-south-1'

Returns:

Type Description
str

The corresponding HTTPS URL.

Examples:

1
2
3
4
>>> s3_url = "s3://deafrica-services/crop_mask/northern/x187/y109/2019--P1Y/crop_mask_x187y109_2019--P1Y_mask.tif"
>>> https_url = s3_to_https(s3_url, region="af-south-1")
>>> print(https_url)
# https://deafrica-services.s3.af-south-1.amazonaws.com/crop_mask/northern/x187/y109/2019--P1Y/crop_mask_x187y109_2019--P1Y_mask.tif

sanitize_geojson(obj)

Recursively converts NumPy types in a GeoJSON-like object to native Python types.

GeoDataFrame.geo_interface can leave NumPy arrays/scalars in feature properties (e.g. list-valued columns are read back as ndarrays), which are not JSON serializable and break widget serialization. This makes the object safe for json.dumps.

Parameters:

Name Type Description Default
obj Any

A GeoJSON dict, list, or scalar that may contain NumPy types.

required

Returns:

Name Type Description
Any Any

The same structure with NumPy arrays converted to lists and NumPy

Any

scalars to native Python types.

save_colorbar(out_fig=None, width=4.0, height=0.3, vmin=0, vmax=1.0, palette=None, vis_params=None, cmap='gray', discrete=False, label=None, label_size=10, label_weight='normal', tick_size=8, bg_color='white', orientation='horizontal', dpi='figure', transparent=False, show_colorbar=True, **kwargs)

Create a standalone colorbar and save it as an image.

Parameters:

Name Type Description Default
out_fig str

Path to the output image.

None
width float

Width of the colorbar in inches. Default is 4.0.

4.0
height float

Height of the colorbar in inches. Default is 0.3.

0.3
vmin float

Minimum value of the colorbar. Default is 0.

0
vmax float

Maximum value of the colorbar. Default is 1.0.

1.0
palette list

List of colors to use for the colorbar. It can also be a cmap name, such as ndvi, ndwi, dem, coolwarm. Default is None.

None
vis_params dict

Visualization parameters as a dictionary. See https://developers.google.com/earth-engine/guides/image_visualization for options.

None
cmap str

Matplotlib colormap. Defaults to "gray". See https://matplotlib.org/3.3.4/tutorials/colors/colormaps.html#sphx-glr-tutorials-colors-colormaps-py for options.

'gray'
discrete bool

Whether to create a discrete colorbar. Defaults to False.

False
label str

Label for the colorbar. Defaults to None.

None
label_size int

Font size for the colorbar label. Defaults to 12.

10
label_weight str

Font weight for the colorbar label, can be "normal", "bold", etc. Defaults to "normal".

'normal'
tick_size int

Font size for the colorbar tick labels. Defaults to 10.

8
bg_color str

Background color for the colorbar. Defaults to "white".

'white'
orientation str

Orientation of the colorbar, such as "vertical" and "horizontal". Defaults to "horizontal".

'horizontal'
dpi float | str

The resolution in dots per inch. If 'figure', use the figure's dpi value. Defaults to "figure".

'figure'
transparent bool

Whether to make the background transparent. Defaults to False.

False
show_colorbar bool

Whether to show the colorbar. Defaults to True.

True
**kwargs Any

Other keyword arguments to pass to matplotlib.pyplot.savefig().

{}

Returns:

Type Description

Path to the output image.

save_data(data, file_ext=None, file_name=None)

Save data in the memory to a file.

Parameters:

Name Type Description Default
data object

The data to be saved.

required
file_ext str

The file extension of the file.

None
file_name str

The name of the file to be saved. Defaults to None.

None

Returns:

Type Description

The path of the file.

save_map(m)

Saves the map as HTML, JPG, or PNG.

Parameters:

Name Type Description Default
m Map

The leafmap Map object.

required

screen_capture(outfile, monitor=1)

Takes a full screenshot of the selected monitor.

Parameters:

Name Type Description Default
outfile str

The output file path to the screenshot.

required
monitor int

The monitor to take the screenshot. Defaults to 1.

1

search_basemaps(m)

The widget for search XYZ tile services.

Parameters:

Name Type Description Default
m Map

The leaflet Map object. Defaults to None.

required

Returns:

Name Type Description
ipywidgets

The tool GUI widget.

search_geojson_gui(m)

Generates a tool GUI template using ipywidgets.

Parameters:

Name Type Description Default
m Map

The leaflet Map object. Defaults to None.

required

Returns:

Name Type Description
ipywidgets

The tool GUI widget.

search_mapillary_images(lon=None, lat=None, radius=5e-05, bbox=None, limit=2000, access_token=None)

Retrieves Mapillary image IDs near the specified test point within a bounding box.

Parameters:

Name Type Description Default
lon float

Longitude of the test point. Defaults to None.

None
lat float

Latitude of the test point. Defaults to None.

None
radius float

Radius to create the bounding box. Defaults to 0.00005.

5e-05
bbox Union[str, List[float]]

Bounding box coordinates. Defaults to None.

None
limit int

Maximum number of image IDs to retrieve. Defaults to 2000.

2000
access_token str

Mapillary API access token. Defaults to None.

None

Returns:

Type Description
List[str]

JSON response from the Mapillary API containing image IDs.

search_qms(keyword, limit=10, list_only=True, add_prefix=True)

Search for QMS tile providers from Quick Map Services.

Parameters:

Name Type Description Default
keyword str

The keyword to search for.

required
limit int

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

10
list_only bool

If True, only the list of services will be returned. Defaults to True.

True
add_prefix bool

If True, the prefix "qms." will be added to the service name. Defaults to True.

True

Returns:

Type Description

A list of QMS tile providers.

search_xyz_services(keyword, name=None, list_only=True, add_prefix=True)

Search for XYZ tile providers from xyzservices.

Parameters:

Name Type Description Default
keyword str

The keyword to search for.

required
name str

The name of the xyz tile. Defaults to None.

None
list_only bool

If True, only the list of services will be returned. Defaults to True.

True
add_prefix bool

If True, the prefix "xyz." will be added to the service name. Defaults to True.

True

Returns:

Type Description

A list of XYZ tile providers.

select_largest(source, column, count=1, output=None, **kwargs)

Select the largest features in a GeoDataFrame based on a column.

Parameters:

Name Type Description Default
source str | GeoDataFrame

The path to the vector file or a GeoDataFrame.

required
column str

The column to sort by.

required
count int

The number of features to select. Defaults to 1.

1
output str

The path to the output vector file. Defaults to None.

None

Returns:

Type Description

The path to the output vector file.

select_table_gui(m=None)

GUI for selecting layers to display attribute table.

Parameters:

Name Type Description Default
m Map

The leaflet Map object. Defaults to None.

None

Returns:

Name Type Description
ipywidgets

The tool GUI widget.

set_api_key(key, name='GOOGLE_MAPS_API_KEY')

Sets the Google Maps API key. You can generate one from https://bit.ly/3sw0THG.

Parameters:

Name Type Description Default
key str

The Google Maps API key.

required
name str

The name of the environment variable. Defaults to "GOOGLE_MAPS_API_KEY".

'GOOGLE_MAPS_API_KEY'

set_proj_lib_path(verbose=False)

Set the PROJ_LIB and GDAL_DATA environment variables based on the current conda environment.

This function attempts to locate and set the correct paths for PROJ_LIB and GDAL_DATA by checking multiple possible locations within the conda environment structure.

Parameters:

Name Type Description Default
verbose bool

If True, print additional information during the process.

False

Returns:

Type Description

True if both paths were set successfully, False otherwise.

set_proxy(port=1080, ip='http://127.0.0.1')

Sets proxy if needed. This is only needed for countries where Google services are not available.

Parameters:

Name Type Description Default
port int

The proxy port number. Defaults to 1080.

1080
ip str

The IP address. Defaults to 'http://127.0.0.1'.

'http://127.0.0.1'

show_html(html)

Shows HTML within Jupyter notebook.

Parameters:

Name Type Description Default
html str

File path or HTML string.

required

Raises:

Type Description
FileNotFoundError

If the file does not exist.

Returns:

Type Description
None

An ipywidgets.HTML widget.

show_image(img_path, width=None, height=None)

Shows an image within Jupyter notebook.

Parameters:

Name Type Description Default
img_path str

The image file path.

required
width int

Width of the image in pixels. Defaults to None.

None
height int

Height of the image in pixels. Defaults to None.

None

show_table_gui(m, df)

Open the attribute table GUI.

Parameters:

Name Type Description Default
m Map

The leaflet Map object

required

Returns:

Name Type Description
ipywidgets

The tool GUI widget.

show_youtube_video(url, width=800, height=450, allow_autoplay=False, **kwargs)

Displays a Youtube video in a Jupyter notebook.

Parameters:

Name Type Description Default
url string

a link to a Youtube video.

required
width int

the width of the video. Defaults to 800.

800
height int

the height of the video. Defaults to 600.

450
allow_autoplay bool

whether to allow autoplay. Defaults to False.

False
**kwargs Any

further arguments for IPython.display.YouTubeVideo

{}

Returns:

Type Description

A video that is displayed in your notebook.

shp_to_gdf(in_shp)

Converts a shapefile to Geopandas dataframe.

Parameters:

Name Type Description Default
in_shp str

File path to the input shapefile.

required

Raises:

Type Description
FileNotFoundError

The provided shp could not be found.

Returns:

Type Description
GeoDataFrame

A GeoPandas GeoDataFrame.

shp_to_geojson(in_shp, output=None, encoding='utf-8', crs='EPSG:4326', **kwargs)

Converts a shapefile to GeoJSON.

Parameters:

Name Type Description Default
in_shp str

File path of the input shapefile.

required
output str

File path of the output GeoJSON. Defaults to None.

None

Returns:

Type Description
Optional[dict]

The JSON object representing the shapefile.

skip_mkdocs_build()

Skips the MkDocs build if the USE_MKDOCS environment variable is set.

Returns:

Type Description

Whether to skip the MkDocs build.

sort_files(files, names=None, fill_na=True)

Sorts a list of files based on a list of names.

If names is None, the function sorts the list of files in-place and returns the sorted list. If names is provided, the function filters the list of files to include only those that contain any of the names in the list, and returns the filtered list.

Parameters:

Name Type Description Default
files List[str]

The list of files to sort or filter.

required
names Optional[List[str]]

The list of names to filter by. Defaults to None.

None

Returns:

Type Description
List[str]

The sorted or filtered list of files.

split_basemaps(m, layers_dict=None, left_name=None, right_name=None, width='120px', **kwargs)

Create a split-panel map for visualizing two maps.

Parameters:

Name Type Description Default
m Map

An ipyleaflet map object.

required
layers_dict dict

A dictionary of TileLayers. Defaults to None.

None
left_name str

The default value of the left dropdown list. Defaults to None.

None
right_name str

The default value of the right dropdown list. Defaults to None.

None
width str

The width of the dropdown list. Defaults to "120px".

'120px'

split_parquet_by_geometries(input_parquet, output_dir, input_vector, column, filename_prefix='', filename_suffix='', driver='PARQUET', verbose=True, **kwargs)

Split a Parquet file containing geometries based on intersection with features from a vector file.

Parameters:

Name Type Description Default
input_parquet str

Path to the input Parquet file containing geometries.

required
output_dir str

Directory to save the split files.

required
input_vector str

Path to the vector file containing geometries to split by.

required
column str

Column name in the vector file to use for splitting.

required
filename_prefix str

Prefix for output filenames.

''
filename_suffix str

Suffix for output filenames.

''
driver str

Output format driver (e.g., "PARQUET", "GPKG").

'PARQUET'
verbose bool

Whether to print progress information.

True
**kwargs

Additional arguments.

{}

Raises:

Type Description
ParserException

If there's a syntax error in the SQL query.

split_raster(filename, out_dir, tile_size=256, overlap=0, prefix='tile')

Split a raster into tiles.

Parameters:

Name Type Description Default
filename str

The path or http URL to the raster file.

required
out_dir str

The path to the output directory.

required
tile_size int | tuple

The size of the tiles. Can be an integer or a tuple of (width, height). Defaults to 256.

256
overlap int

The number of pixels to overlap between tiles. Defaults to 0.

0
prefix str

The prefix of the output tiles. Defaults to "tile".

'tile'

Raises:

Type Description
ImportError

Raised if GDAL is not installed.

st_download_button(label, data, file_name=None, mime=None, key=None, help=None, on_click=None, args=None, csv_sep=',', **kwargs)

Streamlit function to create a download button.

Parameters:

Name Type Description Default
label str

A short label explaining to the user what this button is for..

required
data str | list

The contents of the file to be downloaded. See example below for caching techniques to avoid recomputing this data unnecessarily.

required
file_name str

An optional string to use as the name of the file to be downloaded, such as 'my_file.csv'. If not specified, the name will be automatically generated. Defaults to None.

None
mime str

The MIME type of the data. If None, defaults to "text/plain" (if data is of type str or is a textual file) or "application/octet-stream" (if data is of type bytes or is a binary file). Defaults to None.

None
key str

An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Defaults to None.

None
help str

An optional tooltip that gets displayed when the button is hovered over. Defaults to None.

None
on_click str

An optional callback invoked when this button is clicked. Defaults to None.

None
args list

An optional tuple of args to pass to the callback. Defaults to None.

None
kwargs dict

An optional tuple of args to pass to the callback.

{}

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://titiler.opengeos.org", "planetary-computer", "pc". Defaults to None.

None

Returns:

Name Type Description
list List

A list of assets.

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://titiler.opengeos.org", "planetary-computer", "pc". Defaults to None.

None

Returns:

Name Type Description
list List

A list of band names

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://titiler.opengeos.org", "planetary-computer", "pc". Defaults to None.

None

Returns:

Name Type Description
list List

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

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://titiler.opengeos.org", "planetary-computer", "pc". Defaults to None.

None

Returns:

Name Type Description
tuple Tuple[float, float]

A tuple representing (longitude, latitude)

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.

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.

stac_custom_gui(m=None, button_width='85px', backend='ipyleaflet', **kwargs)

Generates a tool GUI template using ipywidgets.

Parameters:

Name Type Description Default
m Map

The leaflet Map object. Defaults to None.

None
button_width str

The button width. Defaults to "85px".

'85px'
**kwargs

Additional keyword arguments that will be passed to the pystac Client.open() function.

{}

Returns:

Name Type Description
ipywidgets

The tool GUI widget.

stac_gui(m=None, position='topright', opened=True, backend='ipyleaflet', **kwargs)

Generates a tool GUI template using ipywidgets.

Parameters:

Name Type Description Default
m Map

The leaflet Map object. Defaults to None.

None

Returns:

Name Type Description
ipywidgets

The tool GUI widget.

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://titiler.opengeos.org", "planetary-computer", "pc". Defaults to None.

None

Returns:

Name Type Description
list List

A dictionary of band info.

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://titiler.opengeos.org", "planetary-computer", "pc". Defaults to None.

None

Returns:

Name Type Description
list List

A dictionary of band info.

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://titiler.opengeos.org", "planetary-computer", "pc". Defaults to None.

None

Returns:

Name Type Description
list List

A dictionary of band statistics.

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.

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://titiler.opengeos.org", "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.

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.

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.

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.

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.

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.

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.

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://titiler.opengeos.org", "planetary-computer", "pc". Defaults to None.

None

Returns:

Name Type Description
list List

A dictionary of band statistics.

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://titiler.opengeos.org", "https://planetarycomputer.microsoft.com/api/data/v1", "planetary-computer", "pc". Defaults to None.

None

Returns:

Type Description
str

The STAC tile layer URL.

stack_bands(input_files, output_file, resolution=None, dtype=None, temp_vrt='stack.vrt', overwrite=False, compress='DEFLATE', output_format='COG', extra_gdal_translate_args=None)

Stack bands from multiple images into a single multi-band GeoTIFF.

Parameters:

Name Type Description Default
input_files List[str]

List of input image paths.

required
output_file str

Path to the output stacked image.

required
resolution float

Output resolution. If None, inferred from first image.

None
dtype str

Output data type (e.g., "UInt16", "Float32").

None
temp_vrt str

Temporary VRT filename.

'stack.vrt'
overwrite bool

Whether to overwrite the output file.

False
compress str

Compression method.

'DEFLATE'
output_format str

GDAL output format (default is "COG").

'COG'
extra_gdal_translate_args List[str]

Extra arguments for gdal_translate.

None

Returns:

Name Type Description
str str

Path to the output file.

start_duckdb_tile_server(database_path, table_name='features', geom_column='geom', properties=None, port=8000, background=True, quiet=True, cors=True, min_zoom=None, src_crs=None)

Start a Flask server that serves vector tiles from a DuckDB database.

This function creates a Flask web server with a vector tile endpoint that generates Mapbox Vector Tiles (MVT) on-the-fly from a DuckDB database using the ST_AsMVT function. The tiles can be consumed by MapLibre GL JS and other vector tile clients.

If the specified port is already in use, the function will automatically find the next available port.

Parameters:

Name Type Description Default
database_path str

Path to the DuckDB database file.

required
table_name str

Name of the table containing the spatial data. Defaults to "features".

'features'
geom_column str

Name of the geometry column. Defaults to "geom".

'geom'
properties list

List of property columns to include in tiles. If None, includes all columns except geometry. Defaults to None.

None
port int

Port number for the server. Defaults to 8000. If the port is in use, will automatically use the next available port.

8000
background bool

Whether to run the server in a background thread. Defaults to True.

True
quiet bool

If True, suppress server logs. Defaults to True.

True
cors bool

Whether to enable CORS. Defaults to True.

True
min_zoom int

Minimum zoom level at which to query and serve tiles. Below this zoom level, empty tiles will be returned, preventing memory issues with large datasets. If None, tiles will be served at all zoom levels. Defaults to None.

None
src_crs str

Source CRS of the data in the database as an EPSG code (e.g., 'EPSG:26918', 'EPSG:4326'). If provided, geometries will be transformed on-the-fly from this CRS to Web Mercator when serving tiles. Only needed if the data in the database is not already in Web Mercator (EPSG:3857). Defaults to None.

None

Returns:

Name Type Description
int int

The actual port number being used by the server.

Raises:

Type Description
ImportError

If required modules (flask, duckdb) are not installed.

Example

import leafmap

Initialize database

db_path = leafmap.init_duckdb_tiles("data.geojson", database_path="tiles.db")

Start tile server

actual_port = leafmap.start_duckdb_tile_server( ... database_path=db_path, ... table_name="features", ... port=8000 ... ) print(f"Server running on port {actual_port}")

Server is now running at http://127.0.0.1:{actual_port}/tiles/{z}/{x}/{y}.pbf

start_martin(db_url=None, *, mbtiles=None, pmtiles=None, port=3000, cache_dir=None, extra_args=None, pidfile=None, martin_version='v0.20.0')

Start Martin v0.20.0 serving from any combo of: - PostgreSQL (db_url) - MBTiles (mbtiles=[...]) - PMTiles (pmtiles=[...])

Parameters:

Name Type Description Default
db_url Optional[str]

The URL of the PostgreSQL database.

None
mbtiles Optional[list[Union[str, Path]]]

A list of MBTiles files.

None
pmtiles Optional[list[Union[str, Path]]]

A list of PMTiles files.

None
port int

The port to listen on.

3000
cache_dir Optional[Union[str, Path]]

The directory to cache the Martin binary.

None
extra_args Optional[list[str]]

Extra arguments to pass to the Martin binary.

None
pidfile Optional[Union[str, Path]]

The file to write the PID to.

None
martin_version str

The version of Martin to use.

'v0.20.0'

Returns:

Type Description
Popen

A subprocess.Popen object representing the Martin process.

Popen

Also writes a PID file for stop_martin().

start_server(directory=None, port=8000, background=True, quiet=True)

Start a simple web server to serve files from the specified directory with directory listing and CORS support. Optionally, run the server asynchronously in a background thread.

Parameters:

Name Type Description Default
directory str

The directory from which files will be served.

None
port int

The port on which the web server will run. Defaults to 8000.

8000
background bool

Whether to run the server in a separate background thread. Defaults to True.

True
quiet bool

If True, suppress the log output. Defaults to True.

True

Raises:

Type Description
ImportError

If required modules are not found.

Exception

Catches other unexpected errors during execution.

Returns:

Type Description
None

None. The function runs the server indefinitely until manually stopped.

stop_martin(proc=None, pidfile=None, timeout=10.0, cache_dir=None, martin_version='v0.18.1')

Stop Martin started via start_martin(). Use the Popen handle if you have it, otherwise it falls back to the PID file.

Parameters:

Name Type Description Default
proc Optional[Popen]

The subprocess.Popen object representing the Martin process.

None
pidfile Optional[Union[str, Path]]

The file to read the PID from.

None
timeout float

The timeout in seconds to wait for the Martin process to terminate.

10.0
cache_dir Optional[Union[str, Path]]

The directory to cache the Martin binary.

None
martin_version str

The version of Martin to use.

'v0.18.1'

Returns:

Type Description

None

Raises:

Type Description
TimeoutExpired

If the Martin process does not terminate within the timeout.

streamlit_legend(html, width=None, height=None, scrolling=True)

Streamlit function to display a legend.

Parameters:

Name Type Description Default
html str

The HTML string of the legend.

required
width str

The width of the legend. Defaults to None.

None
height str

The height of the legend. Defaults to None.

None
scrolling bool

Whether to allow scrolling in the legend. Defaults to True.

True

system_fonts(show_full_path=False)

Gets a list of system fonts

1
2
3
4
# Common font locations:
# Linux: /usr/share/fonts/TTF/
# Windows: C:/Windows/Fonts
# macOS:  System > Library > Fonts

Parameters:

Name Type Description Default
show_full_path bool

Whether to show the full path of each system font. Defaults to False.

False

Returns:

Type Description
List

A list of system fonts.

temp_file_path(extension)

Returns a temporary file path.

Parameters:

Name Type Description Default
extension str

The file extension.

required

Returns:

Type Description

The temporary file path.

tif_to_jp2(filename, output, creationOptions=None)

Converts a GeoTIFF to JPEG2000.

Parameters:

Name Type Description Default
filename str

The path to the GeoTIFF file.

required
output str

The path to the output JPEG2000 file.

required
creationOptions list

A list of creation options for the JPEG2000 file. See https://gdal.org/drivers/raster/jp2openjpeg.html. For example, to specify the compression ratio, use ["QUALITY=20"]. A value of 20 means the file will be 20% of the size in comparison to uncompressed data.

None

time_slider(m, layers=None, labels=None, time_interval=1, position='bottomright', slider_length='150px', zoom_to_layer=False, tile_args=None, **kwargs)

Adds a time slider to the map.

Parameters:

Name Type Description Default
layers dict

The dictionary containing a set of XYZ tile layers.

None
labels list

The list of labels to be used for the time series. Defaults to None.

None
time_interval int

Time interval in seconds. Defaults to 1.

1
position str

Position to place the time slider, can be any of ['topleft', 'topright', 'bottomleft', 'bottomright']. Defaults to "bottomright".

'bottomright'
slider_length str

Length of the time slider. Defaults to "150px".

'150px'
zoom_to_layer bool

Whether to zoom to the extent of the layer. Defaults to False.

False
tile_args dict

Additional arguments to pass to the get_local_tile_layer function. Defaults to None.

None

time_slider_for_gdf(m, gdf, time_columns=None, labels=None, time_interval=1, position='bottomright', slider_length='150px', zoom_to_layer=False, style=None, **kwargs)

Adds a time slider to the map for visualizing vector time series data.

Parameters:

Name Type Description Default
m

The leafmap.Map object

required
gdf GeoDataFrame

The GeoDataFrame with time series data stored as color codes in columns

required
time_columns list

List of column names containing the time series data (e.g., dates)

None
labels list

The list of labels to be used for the time series. Defaults to time_columns.

None
time_interval int

Time interval in seconds. Defaults to 1.

1
position str

Position to place the time slider. Defaults to "bottomright".

'bottomright'
slider_length str

Length of the time slider. Defaults to "150px".

'150px'
zoom_to_layer bool

Whether to zoom to the extent of the layer. Defaults to False.

False
style dict

Base style for the GeoJSON layer. Defaults to None.

None

to_hex_colors(colors)

Adds # to a list of hex color codes.

Parameters:

Name Type Description Default
colors list

A list of hex color codes.

required

Returns:

Type Description

A list of hex color codes prefixed with #.

tool_header_template(m, opened=True)

Create a toolbar widget.

Parameters:

Name Type Description Default
m Map

The geemap.Map instance. Defaults to None.

required
opened bool

Whether to open the toolbar. Defaults to True.

True

tool_template(m, opened=True)

Generates a tool GUI template using ipywidgets. Icons can be found at https://fontawesome.com/v4/icons

Parameters:

Name Type Description Default
m Map

The leaflet Map object. Defaults to None.

required
opened bool

Whether to open the toolbar. Defaults to True.

True

Returns:

Type Description
Optional[Widget]

Optional[ipywidgets]: The tool GUI widget, or None if map object is provide. (Assuming it should will be return the widget in all cases) Or, if it always return a widget, the return type should ipywidgets.

transform_bbox_coords(bbox, src_crs, dst_crs, **kwargs)

Transforms the coordinates of a bounding box [x1, y1, x2, y2] from one CRS to another.

Parameters:

Name Type Description Default
bbox list | tuple

The bounding box [x1, y1, x2, y2] coordinates.

required
src_crs str

The source CRS, e.g., "EPSG:4326".

required
dst_crs str

The destination CRS, e.g., "EPSG:3857".

required

Returns:

Type Description

The transformed bounding box [x1, y1, x2, y2] coordinates.

transform_coords(x, y, src_crs, dst_crs, **kwargs)

Transform coordinates from one CRS to another.

Parameters:

Name Type Description Default
x float

The x coordinate.

required
y float

The y coordinate.

required
src_crs str

The source CRS, e.g., "EPSG:4326".

required
dst_crs str

The destination CRS, e.g., "EPSG:3857".

required

Returns:

Type Description

The transformed coordinates in the format of (x, y).

update_package()

Updates the leafmap package from the leafmap GitHub repository without the need to use pip or conda. In this way, I don't have to keep updating pypi and conda-forge with every minor update of the package.

upload_to_imgur(in_gif)

Uploads an image to imgur.com

Parameters:

Name Type Description Default
in_gif str

The file path to the image.

required

vector_area(vector, unit='m2', crs='epsg:3857')

Calculate the area of a vector.

Parameters:

Name Type Description Default
vector str

A local path or HTTP URL to a vector.

required
unit str

The unit of the area, can be 'm2', 'km2', 'ha', or 'acres'. Defaults to 'm2'.

'm2'

Returns:

Type Description

The area of the vector.

vector_col_names(filename, **kwargs)

Retrieves the column names of a vector attribute table.

Parameters:

Name Type Description Default
filename str

The input file path.

required

Returns:

Type Description
List[str]

The list of column names.

vector_geom_type(data, first_only=True, **kwargs)

Returns the geometry type of a vector dataset.

Parameters:

Name Type Description Default
data GeoDataFrame

A GeoDataFrame.

required
first_only bool

Whether to return the geometry type of the first feature in the GeoDataFrame. Defaults to True.

True
kwargs Any

Additional keyword arguments to pass to the geopandas.read_file function.

{}

Returns:

Type Description

The geometry type of the GeoDataFrame, such as Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon. For more info, see https://shapely.readthedocs.io/en/stable/manual.html

vector_set_crs(source, output=None, crs='EPSG:4326', **kwargs)

Set CRS of a vector file.

Parameters:

Name Type Description Default
source str | GeoDataFrame

The path to the vector file or a GeoDataFrame.

required
output str

The path to the output vector file. Defaults to None.

None
crs str

The CRS to set. Defaults to "EPSG:4326".

'EPSG:4326'

Returns:

Type Description

The GeoDataFrame with the new CRS.

vector_to_geojson(filename, out_geojson=None, bbox=None, mask=None, rows=None, epsg='4326', encoding='utf-8', **kwargs)

Converts any geopandas-supported vector dataset to GeoJSON.

Parameters:

Name Type Description Default
filename str

Either the absolute or relative path to the file or URL to be opened, or any object with a read() method (such as an open file or StringIO).

required
out_geojson str

The file path to the output GeoJSON. Defaults to None.

None
bbox tuple | GeoDataFrame or GeoSeries | shapely Geometry

Filter features by given bounding box, GeoSeries, GeoDataFrame or a shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with mask. Defaults to None.

None
mask dict | GeoDataFrame or GeoSeries | shapely Geometry

Filter for features that intersect with the given dict-like geojson geometry, GeoSeries, GeoDataFrame or shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with bbox. Defaults to None.

None
rows int or slice

Load in specific rows by passing an integer (first n rows) or a slice() object.. Defaults to None.

None
epsg str

The EPSG number to convert to. Defaults to "4326".

'4326'
encoding str

The encoding of the input file. Defaults to "utf-8".

'utf-8'

Raises:

Type Description
ValueError

When the output file path is invalid.

Returns:

Type Description
Optional[dict]

A dictionary containing the GeoJSON.

vector_to_geojson_batch(input_dir, output_dir=None, file_ext='.shp', **kwargs)

Converts all vector files in a directory to GeoJSON format in batch.

Parameters:

Name Type Description Default
input_dir str

The directory containing the input vector files.

required
output_dir str

The directory to save the converted GeoPackage files. If not provided, the input directory will be used. Defaults to None.

None
file_ext str

The file extension of the input vector files (e.g., ".shp"). Defaults to ".shp".

'.shp'
**kwargs Any

Additional keyword arguments to be passed to the glob.glob function for file matching.

{}

Returns:

Type Description

None

Example

vector_to_geojson_batch("input_directory", "output_directory", ".shp")

vector_to_gif(filename, out_gif, colname, vmin=None, vmax=None, step=1, facecolor='black', figsize=(10, 8), padding=3, title=None, add_text=True, xy=('1%', '1%'), fontsize=20, add_progress_bar=True, progress_bar_color='blue', progress_bar_height=5, dpi=300, fps=10, loop=0, mp4=False, keep_png=False, verbose=True, open_args={}, plot_args={})

Convert a vector to a gif. This function was inspired by by Johannes Uhl's shapefile2gif repo at https://github.com/johannesuhl/shapefile2gif. Credits to Johannes Uhl.

Parameters:

Name Type Description Default
filename str

The input vector file. Can be a directory path or http URL, e.g., "https://i.imgur.com/ZWSZC5z.gif"

required
out_gif str

The output gif file.

required
colname str

The column name of the vector that contains numerical values.

required
vmin float

The minimum value to filter the data. Defaults to None.

None
vmax float

The maximum value to filter the data. Defaults to None.

None
step float

The step to filter the data. Defaults to 1.

1
facecolor str

The color to visualize the data. Defaults to "black".

'black'
figsize tuple

The figure size. Defaults to (10, 8).

(10, 8)
padding int

The padding of the figure tight_layout. Defaults to 3.

3
title str

The title of the figure. Defaults to None.

None
add_text bool

Whether to add text to the figure. Defaults to True.

True
xy tuple

The position of the text from the lower-left corner. Defaults to ("1%", "1%").

('1%', '1%')
fontsize int

The font size of the text. Defaults to 20.

20
add_progress_bar bool

Whether to add a progress bar to the figure. Defaults to True.

True
progress_bar_color str

The color of the progress bar. Defaults to "blue".

'blue'
progress_bar_height int

The height of the progress bar. Defaults to 5.

5
dpi int

The dpi of the figure. Defaults to 300.

300
fps int

The frames per second (fps) of the gif. Defaults to 10.

10
loop int

The number of loops of the gif. Defaults to 0, infinite loop.

0
mp4 bool

Whether to convert the gif to mp4. Defaults to False.

False
keep_png bool

Whether to keep the png files. Defaults to False.

False
verbose bool

Whether to print the progress. Defaults to True.

True
open_args dict

The arguments for the geopandas.read_file() function. Defaults to {}.

{}
plot_args dict

The arguments for the geopandas.GeoDataFrame.plot() function. Defaults to {}.

{}

vector_to_gpkg_batch(input_dir, output_dir=None, file_ext='.geojson', **kwargs)

Converts all vector files in a directory to GeoPackage format in batch.

Parameters:

Name Type Description Default
input_dir str

The directory containing the input vector files.

required
output_dir str

The directory to save the converted GeoPackage files. If not provided, the input directory will be used. Defaults to None.

None
file_ext str

The file extension of the input vector files (e.g., ".geojson"). Defaults to ".geojson".

'.geojson'
**kwargs Any

Additional keyword arguments to be passed to the glob.glob function for file matching.

{}

Returns:

Type Description

None

Example

vector_to_gpkg_batch("input_directory", "output_directory", ".geojson")

vector_to_mbtiles(source_path, target_path, max_zoom=5, name=None, **kwargs)

Convert a vector dataset to MBTiles format using the ogr2ogr command-line tool.

Parameters:

Name Type Description Default
source_path str

The path to the source vector dataset (GeoPackage, Shapefile, etc.).

required
target_path str

The path to the target MBTiles file to be created.

required
max_zoom int

The maximum zoom level for the MBTiles dataset. Defaults to 5.

5
name str

The name of the MBTiles dataset. Defaults to None.

None
**kwargs

Additional options to be passed as keyword arguments. These options will be used as -dsco options when calling ogr2ogr. See https://gdal.org/drivers/raster/mbtiles.html for a list of options.

{}

Returns:

Type Description
None

None

Raises:

Type Description
CalledProcessError

If the ogr2ogr command fails to execute.

Example

source_path = "countries.gpkg" target_path = "target.mbtiles" name = "My MBTiles" max_zoom = 5 vector_to_mbtiles(source_path, target_path, name=name, max_zoom=max_zoom)

vector_to_parquet(source, output, crs=None, overwrite=False, **kwargs)

Convert a GeoDataFrame or a file containing vector data to Parquet format.

Parameters:

Name Type Description Default
source Union[GeoDataFrame, str]

The source data to convert. It can be either a GeoDataFrame or a file path to the vector data file.

required
output str

The file path where the Parquet file will be saved.

required
crs str

The coordinate reference system (CRS) to use for the output file. Defaults to None.

None
overwrite bool

Whether to overwrite the existing output file. Default is False.

False
**kwargs

Additional keyword arguments to be passed to the to_parquet function of GeoDataFrame.

{}

Returns:

Type Description
None

None

vector_to_parquet_batch(input_dir, output_dir=None, file_ext='.geojson', **kwargs)

Converts all vector files in a directory to Parquet format in batch.

Parameters:

Name Type Description Default
input_dir str

The directory containing the input vector files.

required
output_dir str

The directory to save the converted Parquet files. If not provided, the input directory will be used. Defaults to None.

None
file_ext str

The file extension of the input vector files (e.g., ".geojson"). Defaults to ".geojson".

'.geojson'
**kwargs Any

Additional keyword arguments to be passed to the glob.glob function for file matching.

{}

Returns:

Type Description

None

Example

vector_to_parquet_batch("input_directory", "output_directory", ".geojson")

vector_to_pmtiles(source_path, target_path, max_zoom=15, name=None, **kwargs)

Converts a vector file to PMTiles format.

Parameters:

Name Type Description Default
source_path str

Path to the source vector file.

required
target_path str

Path to the target PMTiles file.

required
max_zoom int

Maximum zoom level for the PMTiles. Defaults to 5.

15
name str

Name of the PMTiles dataset. Defaults to None.

None
**kwargs

Additional keyword arguments to be passed to the underlying conversion functions.

{}

Raises:

Type Description
ValueError

If the target file does not have a .pmtiles extension.

Returns:

Type Description
None

None

vector_to_raster(vector, output, field='FID', assign='last', nodata=True, cell_size=None, base=None, callback=None, verbose=False, to_epsg=None)

Convert a vector to a raster.

Parameters:

Name Type Description Default
vector str | GeoDataFrame

The input vector data, can be a file path or a GeoDataFrame.

required
output str

The output raster file path.

required
field str

Input field name in attribute table. Defaults to 'FID'.

'FID'
assign str

Assignment operation, where multiple points are in the same grid cell; options include 'first', 'last' (default), 'min', 'max', 'sum', 'number'. Defaults to 'last'.

'last'
nodata bool

Background value to set to NoData. Without this flag, it will be set to 0.0.

True
cell_size float

Optionally specified cell size of output raster. Not used when base raster is specified

None
base str

Optionally specified input base raster file. Not used when a cell size is specified. Defaults to None.

None
callback fuct

A callback function to report progress. Defaults to None.

None
verbose bool

Whether to print progress to the console. Defaults to False.

False
to_epsg integer

Optionally specified the EPSG code to reproject the raster to. Defaults to None.

None

view_lidar(filename, cmap='terrain', backend='pyvista', background=None, eye_dome_lighting=False, **kwargs)

View LiDAR data in 3D.

Parameters:

Name Type Description Default
filename str

The filepath to the LiDAR data.

required
cmap str

The colormap to use. Defaults to "terrain". cmap currently does not work for the open3d backend.

'terrain'
backend str

The plotting backend to use, can be pyvista, ipygany, panel, and open3d. Defaults to "pyvista".

'pyvista'
background str

The background color to use. Defaults to None.

None
eye_dome_lighting bool

Whether to use eye dome lighting. Defaults to False.

False

Raises:

Type Description
FileNotFoundError

If the file does not exist.

ValueError

If the backend is not supported.

whiteboxgui(verbose=True, tree=False, reset=False, sandbox_path=None)

Shows the WhiteboxTools GUI.

Parameters:

Name Type Description Default
verbose bool

Whether to show progress info when the tool is running. Defaults to True.

True
tree bool

Whether to use the tree mode toolbox built using ipytree rather than ipywidgets. Defaults to False.

False
reset bool

Whether to regenerate the json file with the dictionary containing the information for all tools. Defaults to False.

False
sandbox_path str

The path to the sandbox folder. Defaults to None.

None

Returns:

Type Description
dict

A toolbox GUI.

widget_template(widget=None, opened=True, show_close_button=True, widget_icon='gear', close_button_icon='times', widget_args={}, close_button_args={}, display_widget=None, m=None, position='topright')

Create a widget template.

Parameters:

Name Type Description Default
widget Widget

The widget to be displayed. Defaults to None.

None
opened bool

Whether to open the toolbar. Defaults to True.

True
show_close_button bool

Whether to show the close button. Defaults to True.

True
widget_icon str

The icon name for the toolbar button. Defaults to 'gear'.

'gear'
close_button_icon str

The icon name for the close button. Defaults to "times".

'times'
widget_args dict

Additional arguments to pass to the toolbar button. Defaults to {}.

{}
close_button_args dict

Additional arguments to pass to the close button. Defaults to {}.

{}
display_widget Widget

The widget to be displayed when the toolbar is clicked.

None
m Map

The geemap.Map instance. Defaults to None.

None
position str

The position of the toolbar. Defaults to "topright".

'topright'

wms_to_geotiff(url, layers, bbox, output, width=None, height=None, scale=None, bbox_crs='EPSG:4326', output_crs=None, format='image/tiff', version='1.1.1', styles='', transparent=True, quiet=False, **kwargs)

Export a GeoTIFF from a WMS service within a specified bounding box and scale.

Parameters:

Name Type Description Default
url str

The URL of the WMS service.

required
layers str

Comma-separated list of WMS layers to request.

required
bbox List[float]

Bounding box in the format [minx, miny, maxx, maxy]. The coordinates should be in the CRS specified by 'bbox_crs'.

required
output str

The output file path for the GeoTIFF.

required
width int

Width of the output image in pixels. If not provided, will be calculated from scale. Either width/height or scale must be provided.

None
height int

Height of the output image in pixels. If not provided, will be calculated from scale. Either width/height or scale must be provided.

None
scale float

The scale (resolution) in units of the output CRS per pixel. For EPSG:4326, this is degrees per pixel. For projected CRS like EPSG:3857, this is meters per pixel. Either width/height or scale must be provided.

None
bbox_crs str

The coordinate reference system of the input bbox. Defaults to "EPSG:4326".

'EPSG:4326'
output_crs str

The coordinate reference system for the output GeoTIFF and WMS request. If None, uses the same CRS as bbox_crs. Defaults to None.

None
format str

The image format to request from WMS. Defaults to "image/tiff". Some WMS servers may support "image/geotiff" or only "image/png".

'image/tiff'
version str

WMS version. Defaults to "1.1.1".

'1.1.1'
styles str

WMS styles parameter. Defaults to "".

''
transparent bool

Request transparent background. Defaults to True.

True
quiet bool

Suppress output messages. Defaults to False.

False
**kwargs Any

Additional keyword arguments to pass to the WMS GetMap request.

{}

Returns:

Name Type Description
str str

The output file path.

Raises:

Type Description
ValueError

If neither width/height nor scale is provided.

ImportError

If required packages are not installed.

Exception

If the WMS request fails.

Example

url = "https://img.nj.gov/imagerywms/Natural2015" layers = "Natural2015" bbox = [-74.6, 40.5, -74.4, 40.7] # [minx, miny, maxx, maxy] in EPSG:4326 wms_to_geotiff(url, layers, bbox, "output.tif", scale=0.0001)

Export with different output CRS

wms_to_geotiff(url, layers, bbox, "output_3857.tif", scale=10, output_crs="EPSG:3857")

write_image_colormap(image, colormap, output_path=None)

Apply or update a colormap to a raster image.

Parameters:

Name Type Description Default
image (str, DatasetReader, DataArray)

The input image. It can be: - A file path to a raster image (string). - A rasterio dataset. - A rioxarray DataArray.

required
colormap dict

A dictionary defining the colormap (value: (R, G, B, A)).

required
output_path str

Path to save the updated raster image. If None, the original file is updated in-memory.

None

Returns:

Type Description

Path to the updated raster image.

Raises:

Type Description
ValueError

If the input image type is unsupported.

write_lidar(source, destination, do_compress=None, laz_backend=None)

Writes to a stream or file.

Parameters:

Name Type Description Default
source str | LasBase

The source data to be written.

required
destination str

The destination filepath.

required
do_compress bool

Flags to indicate if you want to compress the data. Defaults to None.

None
laz_backend str

The laz backend to use. Defaults to None.

None

xarray_to_raster(dataset, filename, **kwargs)

Convert an xarray Dataset to a raster file.

Parameters:

Name Type Description Default
dataset Dataset

The input xarray Dataset to be converted.

required
filename str

The output filename for the raster file.

required
**kwargs Dict[str, Any]

Additional keyword arguments passed to the rio.to_raster() method. See https://corteva.github.io/rioxarray/stable/examples/convert_to_raster.html for more info.

{}

Returns:

Type Description
None

None

xy_to_window(xy)

Converts a list of coordinates to a rasterio window.

Parameters:

Name Type Description Default
xy list

A list of coordinates in the format of [[x1, y1], [x2, y2]]

required

Returns:

Type Description
Tuple[float, float, float, float]

The rasterio window in the format of (col_off, row_off, width, height).

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.

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://titiler.opengeos.org".

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.

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://titiler.opengeos.org".

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.

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)

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://titiler.opengeos.org".

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.

zonal_stats(vectors, raster, layer=0, band_num=1, nodata=None, affine=None, stats=None, all_touched=False, categorical=False, category_map=None, add_stats=None, raster_out=False, prefix=None, geojson_out=False, gdf_out=False, dst_crs=None, open_vector_args={}, open_raster_args={}, **kwargs)

This function wraps rasterstats.zonal_stats and performs reprojection if necessary. See https://pythonhosted.org/rasterstats/rasterstats.html.

Parameters:

Name Type Description Default
vectors str | list | GeoDataFrame

path to an vector source or geo-like python objects.

required
raster str | ndarray

ndarray or path to a GDAL raster source.

required
layer int

If vectors is a path to an fiona source, specify the vector layer to use either by name or number. Defaults to 0

0
band_num int | str

If raster is a GDAL source, the band number to use (counting from 1). defaults to 1.

1
nodata float

If raster is a GDAL source, this value overrides any NODATA value specified in the file's metadata. If None, the file's metadata's NODATA value (if any) will be used. defaults to None.

None
affine Affine

required only for ndarrays, otherwise it is read from src. Defaults to None.

None
stats str | list

Which statistics to calculate for each zone. It can be ['min', 'max', 'mean', 'count']. For more, see https://pythonhosted.org/rasterstats/manual.html#zonal-statistics Defaults to None.

None
all_touched bool

Whether to include every raster cell touched by a geometry, or only those having a center point within the polygon. defaults to False

False
categorical bool

If True, the raster values will be treated as categorical.

False
category_map dict

A dictionary mapping raster values to human-readable categorical names. Only applies when categorical is True

None
add_stats dict

with names and functions of additional stats to compute. Defaults to None.

None
raster_out bool

Include the masked numpy array for each feature?. Defaults to False.

False
prefix str

add a prefix to the keys. Defaults to None.

None
geojson_out bool

Return list of GeoJSON-like features (default: False) Original feature geometry and properties will be retained with zonal stats appended as additional properties. Use with prefix to ensure unique and meaningful property names.. Defaults to False.

False
gdf_out bool

Return a GeoDataFrame. Defaults to False.

False
dst_crs str

The destination CRS. Defaults to None.

None
open_vector_args dict

Pass additional arguments to geopandas.open_file(). Defaults to {}.

{}
open_raster_args dict

Pass additional arguments to rasterio.open(). Defaults to {}.

{}

Returns:

Type Description

The zonal statistics results.

zoom_level_resolution(zoom, latitude=0)

Returns the approximate pixel scale based on zoom level and latutude. See https://blogs.bing.com/maps/2006/02/25/map-control-zoom-levels-gt-resolution

Parameters:

Name Type Description Default
zoom int

The zoom level.

required
latitude float

The latitude. Defaults to 0.

0

Returns:

Type Description

Map resolution in meters.