CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-leafmap

A Python package for geospatial analysis and interactive mapping in a Jupyter environment.

54

0.80x

Evaluation54%

0.80x

Agent success when using this tile

Overview
Eval results
Files

osm-integration.mddocs/

OpenStreetMap Integration

Direct integration with OpenStreetMap data through the Overpass API, enabling querying and visualization of OSM data by address, place, bounding box, or point with comprehensive tag-based filtering and export capabilities.

Capabilities

OSM Data Query by Location

Query OpenStreetMap data using various location-based approaches with comprehensive tag filtering for targeted data extraction.

def osm_gdf_from_address(address, tags, **kwargs):
    """
    Get OSM data for features near an address.
    
    Args:
        address (str): Address to geocode and search around
        tags (dict): OSM tags to filter by (e.g., {'building': True})
        **kwargs: Query options (distance, timeout, etc.)
        
    Returns:
        gpd.GeoDataFrame: OSM features as GeoDataFrame
    """

def osm_gdf_from_place(place, tags, **kwargs):
    """
    Get OSM data within a named place boundary.
    
    Args:
        place (str): Place name to search within
        tags (dict): OSM tags to filter by
        **kwargs: Query options (which_result, timeout, etc.)
        
    Returns:
        gpd.GeoDataFrame: OSM features as GeoDataFrame
    """

def osm_gdf_from_point(point, tags, distance=1000, **kwargs):
    """
    Get OSM data around a specific point.
    
    Args:
        point (tuple): (latitude, longitude) coordinates
        tags (dict): OSM tags to filter by
        distance (float): Search radius in meters
        **kwargs: Query options (timeout, etc.)
        
    Returns:
        gpd.GeoDataFrame: OSM features as GeoDataFrame
    """

def osm_gdf_from_bbox(bbox, tags, **kwargs):
    """
    Get OSM data within a bounding box.
    
    Args:
        bbox (list): Bounding box [minx, miny, maxx, maxy]
        tags (dict): OSM tags to filter by
        **kwargs: Query options (timeout, etc.)
        
    Returns:
        gpd.GeoDataFrame: OSM features as GeoDataFrame
    """

OSM Data Export

Export OSM data directly to various file formats for use in external applications and analysis workflows.

def osm_shp_from_address(address, tags, filename, **kwargs):
    """
    Export OSM data near address to shapefile.
    
    Args:
        address (str): Address to search around
        tags (dict): OSM tags to filter by
        filename (str): Output shapefile path
        **kwargs: Export options (distance, etc.)
        
    Returns:
        str: Path to created shapefile
    """

def osm_shp_from_place(place, tags, filename, **kwargs):
    """
    Export OSM data from place to shapefile.
    
    Args:
        place (str): Place name to search within
        tags (dict): OSM tags to filter by
        filename (str): Output shapefile path
        **kwargs: Export options
        
    Returns:
        str: Path to created shapefile
    """

def osm_shp_from_bbox(bbox, tags, filename, **kwargs):
    """
    Export OSM data from bounding box to shapefile.
    
    Args:
        bbox (list): Bounding box coordinates
        tags (dict): OSM tags to filter by
        filename (str): Output shapefile path
        **kwargs: Export options
        
    Returns:
        str: Path to created shapefile
    """

def osm_geojson_from_address(address, tags, filename, **kwargs):
    """
    Export OSM data near address to GeoJSON.
    
    Args:
        address (str): Address to search around
        tags (dict): OSM tags to filter by
        filename (str): Output GeoJSON path
        **kwargs: Export options (distance, etc.)
        
    Returns:
        str: Path to created GeoJSON file
    """

def osm_geojson_from_place(place, tags, filename, **kwargs):
    """
    Export OSM data from place to GeoJSON.
    
    Args:
        place (str): Place name to search within
        tags (dict): OSM tags to filter by
        filename (str): Output GeoJSON path
        **kwargs: Export options
        
    Returns:
        str: Path to created GeoJSON file
    """

def osm_geojson_from_bbox(bbox, tags, filename, **kwargs):
    """
    Export OSM data from bounding box to GeoJSON.
    
    Args:
        bbox (list): Bounding box coordinates
        tags (dict): OSM tags to filter by
        filename (str): Output GeoJSON path
        **kwargs: Export options
        
    Returns:
        str: Path to created GeoJSON file
    """

OSM Tag Management

Discover and work with OpenStreetMap tags for comprehensive data filtering and feature selection.

def osm_tags_list():
    """
    Get list of common OSM tags and their descriptions.
    
    Returns:
        dict: Dictionary of OSM tags with descriptions and common values
    """

def osm_tag_info(tag_key):
    """
    Get detailed information about specific OSM tag.
    
    Args:
        tag_key (str): OSM tag key (e.g., 'building', 'highway')
        
    Returns:
        dict: Tag information including common values and usage
    """

def validate_osm_tags(tags):
    """
    Validate OSM tag dictionary for proper formatting.
    
    Args:
        tags (dict): OSM tags to validate
        
    Returns:
        bool: True if tags are valid, False otherwise
    """

Map Integration

Add OSM data directly to maps with automatic styling and interactive features.

def add_osm_from_address(self, address, tags, **kwargs):
    """
    Add OSM data near address to map.
    
    Args:
        address (str): Address to search around
        tags (dict): OSM tags to filter by
        **kwargs: Map layer options (style, popup, layer_name, etc.)
    """

def add_osm_from_place(self, place, tags, **kwargs):
    """
    Add OSM data from place to map.
    
    Args:
        place (str): Place name to search within
        tags (dict): OSM tags to filter by
        **kwargs: Map layer options
    """

def add_osm_from_point(self, point, tags, distance=1000, **kwargs):
    """
    Add OSM data around point to map.
    
    Args:
        point (tuple): (latitude, longitude) coordinates
        tags (dict): OSM tags to filter by
        distance (float): Search radius in meters
        **kwargs: Map layer options
    """

def add_osm_from_bbox(self, bbox, tags, **kwargs):
    """
    Add OSM data from bounding box to map.
    
    Args:
        bbox (list): Bounding box coordinates
        tags (dict): OSM tags to filter by
        **kwargs: Map layer options
    """

Common OSM Tags

Building and Infrastructure

# Building tags
building_tags = {
    'building': True,                    # All buildings
    'building': 'residential',          # Residential buildings
    'building': 'commercial',           # Commercial buildings
    'building': 'industrial',           # Industrial buildings
    'building': ['house', 'apartment']  # Specific building types
}

# Infrastructure tags
infrastructure_tags = {
    'amenity': 'hospital',              # Hospitals
    'amenity': 'school',                # Schools
    'amenity': 'restaurant',            # Restaurants
    'tourism': 'hotel',                 # Hotels
    'shop': True                        # All shops
}

Transportation

# Highway/road tags
highway_tags = {
    'highway': True,                    # All roads
    'highway': 'primary',               # Primary roads
    'highway': 'secondary',             # Secondary roads
    'highway': ['trunk', 'primary'],    # Major roads
    'railway': 'rail',                  # Railways
    'railway': 'subway'                 # Subway lines
}

# Public transport
transport_tags = {
    'public_transport': 'stop_position', # Transit stops
    'amenity': 'bus_station',           # Bus stations
    'railway': 'station',               # Train stations
    'aeroway': 'aerodrome'              # Airports
}

Natural Features

# Water features
water_tags = {
    'natural': 'water',                 # Water bodies
    'waterway': 'river',                # Rivers
    'waterway': 'stream',               # Streams
    'landuse': 'reservoir'              # Reservoirs
}

# Land cover
landcover_tags = {
    'natural': 'forest',                # Forests
    'landuse': 'grass',                 # Grassland
    'natural': 'scrub',                 # Scrubland
    'landuse': 'farmland'               # Agricultural land
}

Administrative Boundaries

# Boundary tags
boundary_tags = {
    'boundary': 'administrative',        # Administrative boundaries
    'admin_level': '2',                 # Country boundaries
    'admin_level': '4',                 # State/province boundaries
    'admin_level': '6',                 # County boundaries
    'admin_level': '8'                  # City boundaries
}

# Places
place_tags = {
    'place': 'city',                    # Cities
    'place': 'town',                    # Towns
    'place': 'village',                 # Villages
    'place': 'neighbourhood'            # Neighborhoods
}

Usage Examples

Basic OSM Data Query

import leafmap

# Get buildings around an address
buildings = leafmap.osm_gdf_from_address(
    address='Times Square, New York, NY',
    tags={'building': True},
    distance=500  # 500 meter radius
)

print(f"Found {len(buildings)} buildings")

# Display on map
m = leafmap.Map(center=[40.7580, -73.9855], zoom=16)
m.add_gdf(buildings, 
         layer_name='Buildings',
         style={'fillColor': 'red', 'fillOpacity': 0.5})
m

Transportation Network Analysis

import leafmap

# Get road network for a city
roads = leafmap.osm_gdf_from_place(
    place='Cambridge, Massachusetts, USA',
    tags={'highway': ['primary', 'secondary', 'trunk', 'residential']}
)

# Get transit stops
transit = leafmap.osm_gdf_from_place(
    place='Cambridge, Massachusetts, USA',
    tags={'public_transport': 'stop_position'}
)

# Visualize transportation network
m = leafmap.Map(center=[42.3601, -71.0942], zoom=13)

m.add_gdf(roads, 
         layer_name='Roads',
         style={'color': 'blue', 'weight': 2})

m.add_gdf(transit,
         layer_name='Transit Stops', 
         style={'color': 'red', 'radius': 5})

m

Land Use Analysis

import leafmap

# Define bounding box for study area
bbox = [-122.52, 37.70, -122.35, 37.82]  # San Francisco area

# Get different land use types
parks = leafmap.osm_gdf_from_bbox(
    bbox=bbox,
    tags={'leisure': 'park'}
)

water = leafmap.osm_gdf_from_bbox(
    bbox=bbox,
    tags={'natural': 'water'}
)

buildings = leafmap.osm_gdf_from_bbox(
    bbox=bbox, 
    tags={'building': True}
)

# Create land use map
m = leafmap.Map(center=[37.76, -122.44], zoom=12)

m.add_gdf(water,
         layer_name='Water Bodies',
         style={'fillColor': 'blue', 'fillOpacity': 0.7})

m.add_gdf(parks,
         layer_name='Parks',
         style={'fillColor': 'green', 'fillOpacity': 0.5})

m.add_gdf(buildings,
         layer_name='Buildings', 
         style={'fillColor': 'gray', 'fillOpacity': 0.3})

m

POI (Points of Interest) Discovery

import leafmap

# Get restaurants around a point
restaurants = leafmap.osm_gdf_from_point(
    point=(40.7589, -73.9851),  # Times Square
    tags={'amenity': 'restaurant'},
    distance=1000
)

# Get hotels
hotels = leafmap.osm_gdf_from_point(
    point=(40.7589, -73.9851),
    tags={'tourism': 'hotel'},
    distance=1000
)

# Get attractions
attractions = leafmap.osm_gdf_from_point(
    point=(40.7589, -73.9851),
    tags={'tourism': 'attraction'},
    distance=1000
)

# Create POI map
m = leafmap.Map(center=[40.7589, -73.9851], zoom=15)

m.add_gdf(restaurants,
         layer_name='Restaurants',
         popup=['name', 'cuisine'],
         style={'color': 'red', 'radius': 5})

m.add_gdf(hotels,
         layer_name='Hotels',
         popup=['name', 'stars'],
         style={'color': 'blue', 'radius': 7})

m.add_gdf(attractions,
         layer_name='Attractions',
         popup=['name', 'tourism'],
         style={'color': 'green', 'radius': 8})

m

Export OSM Data

import leafmap

# Export buildings to shapefile
leafmap.osm_shp_from_place(
    place='Boston, Massachusetts, USA',
    tags={'building': True},
    filename='boston_buildings.shp'
)

# Export roads to GeoJSON
leafmap.osm_geojson_from_bbox(
    bbox=[-71.12, 42.35, -71.05, 42.37],
    tags={'highway': ['primary', 'secondary', 'trunk']},
    filename='boston_roads.geojson'
)

print("OSM data exported successfully")

Advanced Tag Usage

import leafmap

# Complex tag queries
complex_tags = {
    'amenity': ['restaurant', 'cafe', 'bar'],  # Multiple values
    'building': True,                          # Any building
    'name': '*'                               # Must have a name
}

# Query with multiple conditions
results = leafmap.osm_gdf_from_place(
    place='Greenwich Village, New York, NY',
    tags=complex_tags
)

# Conditional tags (restaurants with outdoor seating)
outdoor_dining = leafmap.osm_gdf_from_place(
    place='Greenwich Village, New York, NY', 
    tags={
        'amenity': 'restaurant',
        'outdoor_seating': 'yes'
    }
)

# Map results
m = leafmap.Map(center=[40.7335, -74.0027], zoom=15)
m.add_gdf(outdoor_dining,
         layer_name='Outdoor Dining',
         popup=['name', 'cuisine', 'outdoor_seating'])
m

Query Options

Distance and Spatial Options

query_options = {
    'distance': 1000,                   # Search radius in meters
    'timeout': 300,                     # Query timeout in seconds
    'which_result': 1,                  # Which geocoding result to use
    'buffer': 100                       # Additional buffer around area
}

Data Processing Options

processing_options = {
    'retain_all': False,                # Keep all OSM attributes
    'complement': False,                # Complement of the query
    'custom_filter': None              # Custom Overpass filter
}

Export Options

export_options = {
    'driver': 'ESRI Shapefile',        # Output format driver
    'crs': 'EPSG:4326',               # Coordinate reference system
    'encoding': 'utf-8'               # Text encoding
}

OSM Data Structure

Attribute Information

OSM data includes rich attribute information:

  • name: Feature name
  • addr:street, addr:housenumber: Address information
  • phone, website: Contact information
  • opening_hours: Operating hours
  • capacity: Capacity information
  • operator: Operating organization

Geometry Types

OSM features come in different geometry types:

  • Points: POIs, addresses, nodes
  • Lines: Roads, rivers, boundaries
  • Polygons: Buildings, parks, administrative areas
  • Relations: Complex features with multiple parts

Quality Considerations

  • Data completeness: Varies by region and feature type
  • Update frequency: Community-driven, varies by area
  • Attribute consistency: Tag usage may vary between contributors
  • Licensing: Open Database License (ODbL)

Install with Tessl CLI

npx tessl i tessl/pypi-leafmap

docs

basemaps.md

cloud-data.md

data-visualization.md

file-io.md

geospatial-analysis.md

index.md

interactive-maps.md

osm-integration.md

statistical-plotting.md

tile.json