A Python package for geospatial analysis and interactive mapping in a Jupyter environment.
54
Evaluation — 54%
↓ 0.80xAgent success when using this tile
Comprehensive file input/output capabilities supporting various geospatial formats, coordinate transformations, data conversion utilities, and download functionality for seamless data workflows.
Download files from URLs with progress tracking, authentication support, and error handling for reliable data acquisition.
def download_file(url, filename=None, **kwargs):
"""
Download file from URL.
Args:
url (str): URL to download from
filename (str): Local filename for downloaded file
**kwargs: Download options (headers, timeout, verify, etc.)
Returns:
str: Path to downloaded file
"""
def download_from_url(url, out_file, **kwargs):
"""
Advanced download with progress tracking.
Args:
url (str): Source URL
out_file (str): Output file path
**kwargs: Advanced options (chunk_size, progress, resume, etc.)
Returns:
str: Path to downloaded file
"""
def download_folder(url, out_dir, **kwargs):
"""
Download entire folder from URL.
Args:
url (str): Folder URL
out_dir (str): Output directory
**kwargs: Download options (recursive, filters, etc.)
Returns:
list: List of downloaded file paths
"""Read, write, and process raster data in various formats with comprehensive metadata handling and format conversion.
def read_raster(filename, **kwargs):
"""
Read raster file into memory.
Args:
filename (str): Path to raster file
**kwargs: Read options (bands, window, masked, etc.)
Returns:
tuple: (array, metadata) - raster data and metadata
"""
def write_raster(array, filename, **kwargs):
"""
Write raster array to file.
Args:
array (numpy.ndarray): Raster data array
filename (str): Output file path
**kwargs: Write options (crs, transform, compress, etc.)
Returns:
str: Path to written raster file
"""
def raster_info(filename):
"""
Get raster file information.
Args:
filename (str): Path to raster file
Returns:
dict: Raster metadata (bands, CRS, bounds, etc.)
"""
def read_netcdf(filename, variables=None, **kwargs):
"""
Read NetCDF file.
Args:
filename (str): Path to NetCDF file
variables (list): Variables to read
**kwargs: NetCDF read options (time, bbox, etc.)
Returns:
xarray.Dataset: NetCDF data as xarray Dataset
"""Read, write, and convert vector data supporting multiple formats with attribute handling and spatial indexing.
def read_vector(filename, **kwargs):
"""
Read vector file into GeoDataFrame.
Args:
filename (str): Path to vector file
**kwargs: Read options (bbox, rows, columns, etc.)
Returns:
gpd.GeoDataFrame: Vector data as GeoDataFrame
"""
def write_vector(gdf, filename, **kwargs):
"""
Write GeoDataFrame to vector file.
Args:
gdf (gpd.GeoDataFrame): GeoDataFrame to write
filename (str): Output file path
**kwargs: Write options (driver, crs, etc.)
Returns:
str: Path to written vector file
"""
def vector_info(filename):
"""
Get vector file information.
Args:
filename (str): Path to vector file
Returns:
dict: Vector metadata (geometry_type, CRS, bounds, feature_count, etc.)
"""
def read_lidar(filename, **kwargs):
"""
Read LiDAR data file.
Args:
filename (str): Path to LiDAR file (.las, .laz)
**kwargs: LiDAR read options (classification, returns, etc.)
Returns:
dict: LiDAR points and metadata
"""Convert between different geospatial data formats with comprehensive format support and customizable conversion options.
def csv_to_geojson(filename, lat='latitude', lon='longitude', **kwargs):
"""
Convert CSV file to GeoJSON.
Args:
filename (str): Path to CSV file
lat (str): Latitude column name
lon (str): Longitude column name
**kwargs: Conversion options (crs, properties, etc.)
Returns:
str: Path to GeoJSON file
"""
def csv_to_gdf(filename, lat='latitude', lon='longitude', **kwargs):
"""
Convert CSV to GeoDataFrame.
Args:
filename (str): Path to CSV file
lat (str): Latitude column name
lon (str): Longitude column name
**kwargs: Conversion options (crs, etc.)
Returns:
gpd.GeoDataFrame: CSV data as GeoDataFrame
"""
def csv_to_shp(filename, output, lat='latitude', lon='longitude', **kwargs):
"""
Convert CSV to shapefile.
Args:
filename (str): Path to CSV file
output (str): Output shapefile path
lat (str): Latitude column name
lon (str): Longitude column name
**kwargs: Conversion options (crs, etc.)
Returns:
str: Path to created shapefile
"""
def geojson_to_gdf(filename, **kwargs):
"""
Convert GeoJSON to GeoDataFrame.
Args:
filename (str): Path to GeoJSON file
**kwargs: Conversion options
Returns:
gpd.GeoDataFrame: GeoJSON as GeoDataFrame
"""
def shp_to_geojson(filename, **kwargs):
"""
Convert shapefile to GeoJSON.
Args:
filename (str): Path to shapefile
**kwargs: Conversion options (crs, precision, etc.)
Returns:
str: Path to GeoJSON file
"""
def vector_to_geojson(filename, **kwargs):
"""
Convert any vector format to GeoJSON.
Args:
filename (str): Path to vector file
**kwargs: Conversion options
Returns:
str: Path to GeoJSON file
"""Process and convert images with geospatial metadata handling and format optimization.
def image_to_cog(filename, output=None, **kwargs):
"""
Convert image to Cloud Optimized GeoTIFF.
Args:
filename (str): Input image path
output (str): Output COG path
**kwargs: COG creation options (compress, overview, blocksize, etc.)
Returns:
str: Path to COG file
"""
def numpy_to_cog(array, filename, **kwargs):
"""
Convert NumPy array to COG.
Args:
array (numpy.ndarray): Input array
filename (str): Output COG path
**kwargs: COG options (crs, transform, nodata, etc.)
Returns:
str: Path to COG file
"""
def array_to_image(array, filename, **kwargs):
"""
Convert NumPy array to image file.
Args:
array (numpy.ndarray): Input array
filename (str): Output image path
**kwargs: Image options (format, quality, etc.)
Returns:
str: Path to image file
"""
def images_to_gif(images, output, **kwargs):
"""
Convert image sequence to animated GIF.
Args:
images (list): List of image file paths
output (str): Output GIF path
**kwargs: GIF options (duration, loop, optimize, etc.)
Returns:
str: Path to GIF file
"""Handle compressed archives and files with support for various compression formats.
def extract_archive(filename, output_dir=None, **kwargs):
"""
Extract compressed archive.
Args:
filename (str): Path to archive file (.zip, .tar.gz, etc.)
output_dir (str): Extraction directory
**kwargs: Extraction options (members, password, etc.)
Returns:
list: List of extracted file paths
"""
def create_archive(files, output, **kwargs):
"""
Create compressed archive from files.
Args:
files (list): List of file paths to archive
output (str): Output archive path
**kwargs: Archive options (compression, password, etc.)
Returns:
str: Path to created archive
"""
def compress_file(filename, **kwargs):
"""
Compress single file.
Args:
filename (str): File to compress
**kwargs: Compression options (level, format, etc.)
Returns:
str: Path to compressed file
"""Extract and manage metadata from geospatial files with comprehensive format support.
def get_metadata(filename):
"""
Get comprehensive metadata from geospatial file.
Args:
filename (str): Path to geospatial file
Returns:
dict: Complete metadata including CRS, bounds, format info, etc.
"""
def get_crs(filename):
"""
Get coordinate reference system from file.
Args:
filename (str): Path to geospatial file
Returns:
pyproj.CRS: Coordinate reference system
"""
def get_bounds(filename):
"""
Get spatial bounds from file.
Args:
filename (str): Path to geospatial file
Returns:
list: Bounding box [minx, miny, maxx, maxy]
"""
def file_size(filename):
"""
Get file size in human-readable format.
Args:
filename (str): Path to file
Returns:
str: File size (e.g., '15.3 MB')
"""import leafmap
# Download a file
leafmap.download_file(
'https://example.com/data.tif',
'local_data.tif'
)
# Read raster data
array, metadata = leafmap.read_raster('local_data.tif')
print(f"Raster shape: {array.shape}")
print(f"CRS: {metadata['crs']}")
# Read vector data
gdf = leafmap.read_vector('vector_data.shp')
print(f"Features: {len(gdf)}")import leafmap
# Convert CSV with coordinates to GeoJSON
leafmap.csv_to_geojson(
'points.csv',
lat='lat_column',
lon='lon_column',
output='points.geojson'
)
# Convert shapefile to GeoJSON
leafmap.shp_to_geojson(
'boundaries.shp',
output='boundaries.geojson'
)
# Convert to GeoDataFrame for analysis
gdf = leafmap.geojson_to_gdf('points.geojson')
# Process and save back
gdf_processed = gdf[gdf['value'] > 100] # Filter
leafmap.write_vector(gdf_processed, 'filtered_points.gpkg')import leafmap
import numpy as np
# Read raster
array, metadata = leafmap.read_raster('input.tif')
# Process array (example: threshold)
processed = np.where(array > 0.5, 1, 0)
# Convert to COG
leafmap.numpy_to_cog(
processed,
'processed.tif',
crs=metadata['crs'],
transform=metadata['transform'],
compress='lzw'
)
# Create visualization
leafmap.array_to_image(
processed,
'visualization.png'
)import leafmap
import glob
# Find all shapefiles
shapefiles = glob.glob('data/*.shp')
# Convert all to GeoJSON
geojson_files = []
for shp in shapefiles:
geojson = leafmap.shp_to_geojson(shp)
geojson_files.append(geojson)
print(f"Converted {len(geojson_files)} files")
# Combine all into single GeoDataFrame
import geopandas as gpd
combined = gpd.GeoDataFrame()
for geojson in geojson_files:
gdf = leafmap.geojson_to_gdf(geojson)
combined = gpd.concat([combined, gdf])
# Save combined data
leafmap.write_vector(combined, 'combined_data.gpkg')import leafmap
# Read NetCDF file
dataset = leafmap.read_netcdf(
'climate_data.nc',
variables=['temperature', 'precipitation']
)
print(f"Variables: {list(dataset.variables)}")
print(f"Time range: {dataset.time.min().values} to {dataset.time.max().values}")
# Extract single time slice
temp_slice = dataset['temperature'].isel(time=0)
# Convert to raster
leafmap.numpy_to_cog(
temp_slice.values,
'temperature.tif',
crs='EPSG:4326',
bounds=[-180, -90, 180, 90]
)import leafmap
# Read LiDAR file
lidar_data = leafmap.read_lidar(
'pointcloud.las',
classification=[2, 3, 4, 5] # Ground, low/medium/high vegetation
)
print(f"Points: {len(lidar_data['points'])}")
print(f"Classifications: {set(lidar_data['classification'])}")
# Create DEM from ground points
ground_points = lidar_data['points'][lidar_data['classification'] == 2]
# Process to raster (would need additional gridding)
# This is a simplified example
dem_array = process_points_to_grid(ground_points) # Custom function
leafmap.numpy_to_cog(
dem_array,
'dem.tif',
crs='EPSG:32612' # UTM zone
)download_options = {
'headers': {'User-Agent': 'leafmap'}, # Custom headers
'timeout': 300, # Timeout in seconds
'verify': True, # SSL verification
'chunk_size': 8192, # Download chunk size
'resume': True, # Resume interrupted downloads
'progress': True # Show progress bar
}raster_options = {
'bands': [1, 2, 3], # Specific bands to read
'window': ((0, 512), (0, 512)), # Spatial window
'masked': True, # Return masked array
'dtype': 'float32', # Data type
'compress': 'lzw', # Compression method
'tiled': True, # Tiled output
'blockxsize': 512, # Tile width
'blockysize': 512 # Tile height
}vector_options = {
'bbox': [-180, -90, 180, 90], # Bounding box filter
'rows': slice(0, 1000), # Row slice
'columns': ['name', 'value'], # Column selection
'driver': 'GeoJSON', # Output driver
'precision': 6, # Coordinate precision
'drop_z': True # Drop Z coordinates
}Install with Tessl CLI
npx tessl i tessl/pypi-leafmapdocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10