### Python Virtual Environment Setup Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Creates and activates a Python virtual environment, then installs Dash Leaflet. This is the recommended approach for managing project dependencies. ```bash # Create virtual environment python -m venv venv # Activate on Linux/Mac source venv/bin/activate # Activate on Windows virtualenv\Scripts\activate # Install Dash Leaflet pip install dash-leaflet ``` -------------------------------- ### Using uv for Python Environment Setup Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Sets up a Python virtual environment and installs Dash Leaflet using the 'uv' package manager. 'uv' is a modern and fast alternative for managing Python dependencies. ```bash # Create and activate environment uv venv source .venv/bin/activate # Linux/Mac # .venv\Scripts\activate # Windows # Install dependencies uv pip install dash-leaflet ``` -------------------------------- ### Install GeoBuf and Protobuf Dependencies Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Installs the necessary packages for GeoBuf support in dash-leaflet, either using the package's extra or by installing geobuf and google-protobuf directly. ```bash pip install dash-leaflet[geobuf] # or pip install geobuf google-protobuf ``` -------------------------------- ### Install dash-leaflet with GeoBuf support Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/express-utilities.md Install the necessary packages to enable GeoBuf compression. This can be done by installing dash-leaflet with the 'geobuf' extra or installing all optional features. ```bash pip install dash-leaflet[geobuf] # Or install all optional features pip install dash-leaflet[all] ``` -------------------------------- ### Install dash-leaflet Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/INDEX.md Use pip to install the dash-leaflet library. This command installs the package and its dependencies. ```bash pip install dash-leaflet ``` -------------------------------- ### Set up Virtual Environment and Install Python Dependencies Source: https://github.com/emilhe/dash-leaflet/blob/master/README.md Create a virtual environment using uv, activate it, and install Python dependencies. Requires Python 3.12 and uv. ```bash uv venv && source .venv/bin/activate && uv sync ``` -------------------------------- ### Basic Dash Leaflet Map Example Source: https://github.com/emilhe/dash-leaflet/blob/master/README.md A simple Dash application displaying a Leaflet map with a tile layer. Ensure Dash and Dash Leaflet are installed. ```python from dash import Dash import dash_leaflet as dl app = Dash() app.layout = dl.Map(dl.TileLayer(), style={'height': '50vh'}, center=[56, 10], zoom=6) if __name__ == '__main__': app.run_server() ``` -------------------------------- ### Dash Leaflet Installation from Source Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Installs Dash Leaflet by cloning the repository and installing it in editable mode. This is typically used for development or when contributing to the library. ```bash git clone https://github.com/thedirtyfew/dash-leaflet.git cd dash-leaflet pip install -e . ``` -------------------------------- ### Install npm Packages and Run Build Script Source: https://github.com/emilhe/dash-leaflet/blob/master/README.md Install packages via npm, ignoring errors, and then run the build script. This is part of the repository build process. ```bash npm i --ignore-scripts npm run build ``` -------------------------------- ### Install Dash and Dash Leaflet Source: https://github.com/emilhe/dash-leaflet/blob/master/README.md Install the latest versions of Dash and Dash Leaflet using pip. ```bash pip install dash pip install dash-leaflet ``` -------------------------------- ### Install and Run Production Server with Gunicorn Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Installs Gunicorn and runs the Dash Leaflet application using multiple workers for production. It binds to all available network interfaces on port 8000. ```bash pip install gunicorn gunicorn --workers 4 --bind 0.0.0.0:8000 app:server ``` -------------------------------- ### Dash Leaflet Installation with All Optional Features Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Installs Dash Leaflet including all available optional features and dependencies. Use this for full functionality. ```bash # Install all optional features pip install dash-leaflet[all] ``` -------------------------------- ### Example of Rendering Backend Configuration Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/component-reference.md Configure the rendering backend for components like GeoJSON. Use 'canvas' for better performance with many features. ```python from dash_leaflet import GeoJSON GeoJSON( data=..., renderer={'method': 'canvas'} ) ``` -------------------------------- ### Renderer Options Example Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/types.md Specify the vector rendering method (SVG or Canvas) and padding for features. ```python { 'method': 'svg' | 'canvas', # Rendering method 'options': { 'padding': number # Padding around features } } ``` -------------------------------- ### Compressed GeoBuffer Format Example Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-layers.md Example of using the `geojson_to_geobuf` utility to compress GeoJSON data and display it using the 'geobuf' format. ```APIDOC ## Compressed GeoBuffer Format ```python import dash_leaflet as dl from dash_leaflet.express import geojson_to_geobuf # Compress large GeoJSON to GeoBuf compressed = geojson_to_geobuf(geojson_data) dl.GeoJSON( data=compressed, format='geobuf' ) ``` ``` -------------------------------- ### Basic GeoJSON Display Example Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-layers.md A simple example demonstrating how to display GeoJSON data on a map using the GeoJSON component. ```APIDOC ## Basic GeoJSON Display ```python import dash_leaflet as dl geojson_data = { 'type': 'FeatureCollection', 'features': [ { 'type': 'Feature', 'geometry': {'type': 'Point', 'coordinates': [-122.6750, 45.5236]}, 'properties': {'name': 'Portland, OR'} } ] } dl.MapContainer( center=[45.5236, -122.6750], zoom=10, children=[ dl.TileLayer(), dl.GeoJSON(data=geojson_data) ] ) ``` ``` -------------------------------- ### Build Dash Leaflet from Source Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Follow these bash commands to clone the repository, set up a virtual environment, install dependencies, and build the JavaScript and Python components for development. ```bash # Clone repository git clone https://github.com/thedirtyfew/dash-leaflet.git cd dash-leaflet # Create virtual environment uv venv && source .venv/bin/activate # Install dependencies uv sync # Build JavaScript and Python components npm i --ignore-scripts npm run build ``` -------------------------------- ### Build Dependencies Installation for Development Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Installs necessary build dependencies for developing Dash Leaflet from source. This includes Python build tools and Node.js/npm packages. ```bash pip install dash-generate-components npm install webpack ``` -------------------------------- ### ClickData Callback Example Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/types.md Example of a Dash callback that receives and processes clickData to display the clicked coordinates. Requires the 'latlng' key from the clickData object. ```python # Callback receives clickData @app.callback( Output('output', 'children'), Input('map', 'clickData') ) def on_click(clickData): if not clickData: return "Click on the map" lat, lng = clickData['latlng'] return f"Clicked at {lat:.4f}, {lng:.4f}" ``` -------------------------------- ### Basic Dash Leaflet Map Container Example Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md A minimal example demonstrating the required props for a Dash Leaflet MapContainer to render correctly. It includes center coordinates, zoom level, and a TileLayer. ```python import dash_leaflet as dl app.layout = dl.MapContainer( id='map', center=[45.5236, -122.6750], zoom=12, style={'height': '100vh', 'width': '100%'}, children=[ dl.TileLayer() ] ) ``` -------------------------------- ### GeoJSON with Click Events Example Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-layers.md Example showing how to handle click events on GeoJSON features and display information about the clicked feature. ```APIDOC ## With Click Events ```python from dash import callback, Input, Output app.layout = dl.MapContainer( center=[45.5236, -122.6750], zoom=10, children=[ dl.TileLayer(), dl.GeoJSON( id='geojson', data=geojson_data, hoverStyle={'color': 'red', 'weight': 3} ) ] ) @app.callback( Output('output', 'children'), Input('geojson', 'clickData') ) def on_feature_click(clickData): if not clickData: return "Click on a feature" return f"Clicked: {clickData['properties']}" ``` ``` -------------------------------- ### Run Development Server Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Starts the development server for the Dash Leaflet application. By default, it runs on http://localhost:8050. ```bash python app.py ``` -------------------------------- ### Viewport Programmatic Change Example Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/types.md Example of a Dash callback that updates the map's viewport to a specific location with a 'flyTo' animation. Requires 'dash' and 'dash.callback'. ```python from dash import callback, Input, Output @app.callback( Output('map', 'viewport'), Input('zoom-button', 'n_clicks'), prevent_initial_call=True ) def zoom_to_location(n_clicks): return { 'center': [45.5236, -122.6750], 'zoom': 14, 'transition': 'flyTo', 'options': {'duration': 1} # 1 second animation } ``` -------------------------------- ### GeoJSON Options Example Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-layers.md Examples of common Leaflet GeoJSON options that can be passed to the component for styling and behavior customization. ```APIDOC ## GeoJSON Options Inherited from Leaflet GeoJSON. Common options: ```python { 'style': {'color': 'blue', 'weight': 2, 'opacity': 0.7}, 'pointToLayer': '/* JS function */', # Custom marker creation 'onEachFeature': '/* JS function */', # Feature-by-feature callback 'filter': '/* JS function */', # Feature filtering 'coordsToLatLng': '/* JS function */' # Coordinate transformation } ``` ``` -------------------------------- ### Clustering Options Example Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-layers.md Configuration options for enabling and customizing marker clustering using supercluster. ```APIDOC ## Clustering Options GeoJSON supports automatic marker clustering via supercluster: ```python { 'cluster': True, # Enable clustering 'clusterOptions': { 'maxClusterRadius': 80, # Pixel distance for clustering 'maxZoom': 15 # Disable clustering above this zoom } } ``` ``` -------------------------------- ### GeoJSON with Marker Clustering Example Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-layers.md Demonstrates how to enable and configure marker clustering for GeoJSON features. ```APIDOC ## With Marker Clustering ```python dl.GeoJSON( data=geojson_data, options={ 'cluster': True, 'clusterOptions': { 'maxClusterRadius': 80, 'maxZoom': 15 } } ) ``` ``` -------------------------------- ### Polygon Styling Example Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/types.md Applies specific stroke and fill properties to a Polygon. Includes dashed outline. ```python dl.Polygon( positions=[[45.5, -122.7], [45.5, -122.6], [45.6, -122.6]], color='green', weight=2, opacity=0.8, fill=True, fillColor='lightgreen', fillOpacity=0.3, dashArray='5, 5' # Dashed outline ) ``` -------------------------------- ### KeyboardData Callback Example Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/types.md Example of a Dash callback that receives and processes keyboard event data. It extracts the pressed key and checks if the Ctrl key was held down. ```python @app.callback( Output('output', 'children'), Input('map', 'keydownData') ) def on_keydown(keydownData): if not keydownData: return "Press a key" key = keydownData['key'] ctrl = keydownData['ctrlKey'] return f"Pressed {key} (Ctrl: {ctrl})" ``` -------------------------------- ### Nginx Configuration for CSP with Tile Layers Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Provides an example of Nginx configuration to set Content Security Policy (CSP) headers. This is necessary to whitelist domains for tile layers and scripts when CSP is enabled. ```nginx # Tile layers may require additional CSP directives # Ensure tile provider domains are whitelisted # Example nginx config: # add_header Content-Security-Policy " # img-src 'self' tile.openstreetmap.org *.tile.openstreetmap.org; # script-src 'self' 'unsafe-inline' *.js; # "; ``` -------------------------------- ### Install Dash Leaflet in Editable Mode Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Installs the dash-leaflet package in editable mode, which is useful for development. This command is a solution for 'Module Not Found' errors. ```bash pip install -e . ``` -------------------------------- ### Using Environment Variables for API Keys Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Securely use API keys for tile providers like Mapbox by retrieving them from environment variables. This example shows how to set up a TileLayer with an access token. ```python import os from dash_leaflet import TileLayer # Store API keys in environment variables mapbox_token = os.getenv('MAPBOX_ACCESS_TOKEN') # Use in tile layer tile_layer = TileLayer( url='https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', id='mapbox.satellite', accessToken=mapbox_token, attribution='© Mapbox © OpenStreetMap' ) ``` -------------------------------- ### Basic WMSTileLayer Usage in Dash Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-layers.md Example demonstrating how to use the WMSTileLayer component within a Dash Leaflet map. Ensure the correct WMS server URL and layer names are provided. ```python import dash_leaflet as dl dl.MapContainer( center=[45.5236, -122.6750], zoom=10, children=[ dl.WMSTileLayer( url='https://geodesy.nationalmap.gov/arcgis/services/elevation/NationalElevation_DEM/MapServer/WmsServer', layers='0', transparent=True, format='image/png', version='1.3.0' ) ] ) ``` -------------------------------- ### Continuous Colorbar Example Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-colorbar.md Demonstrates a continuous color scale for representing temperature data with custom tick values and labels. This is useful for smooth transitions in numerical data visualization. ```python import dash_leaflet as dl # Temperature scale (0°C to 100°C) colorbar = dl.Colorbar( min=0, max=100, colorscale=['blue', 'cyan', 'green', 'yellow', 'red'], tickValues=[0, 25, 50, 75, 100], tickText=['0°C', '25°C', '50°C', '75°C', '100°C'], label='Temperature (°C)', position='bottomright' ) app.layout = dl.MapContainer( center=[45.5236, -122.6750], zoom=10, children=[ dl.TileLayer(), colorbar ] ) ``` -------------------------------- ### Marker Component Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-vector-features.md This snippet details the Marker component, its parameters, and provides usage examples for default, custom icon, draggable, and event-handling markers. ```APIDOC ## Marker Component ### Description Display clickable/draggable point markers on the map. This component allows for customization of the marker's appearance, behavior, and event handling. ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * **position** (`[latitude, longitude]`) - Required - Geographic coordinates for marker * **icon** (`IconOptions`) - Optional - Icon configuration object (see Icon Options below). Defaults to `L.Icon.Default()`. * **draggable** (`boolean`) - Optional - Allow user to drag marker. Defaults to `false`. * **opacity** (`number`) - Optional - Marker opacity (0-1). Defaults to `1.0`. * **zIndexOffset** (`number`) - Optional - Manually control stacking (high value = on top). Defaults to `0`. * **riseOnHover** (`boolean`) - Optional - Bring marker to top on hover. Defaults to `false`. * **riseOffset** (`number`) - Optional - z-index offset for `riseOnHover`. Defaults to `250`. * **keyboard** (`boolean`) - Optional - Allow focusing via Tab and activating via Enter. Defaults to `true`. * **title** (`string`) - Optional - Browser tooltip on hover. * **alt** (`string`) - Optional - Alt text for icon image (accessibility). * **pane** (`string`) - Optional - Map pane for marker. Defaults to `'markerPane'`. * **shadowPane** (`string`) - Optional - Map pane for shadow. Defaults to `'shadowPane'`. * **n_clicks** (`number`) - Optional - Fires on marker click. * **clickData** (`ClickData`) - Optional - Click location data. * **n_dblclicks** (`number`) - Optional - Fires on marker double-click. * **dblclickData** (`object`) - Optional - Double-click location data. * **eventHandlers** (`object`) - Optional - Custom event handlers. * **disableDefaultEventHandlers** (`boolean`) - Optional - Disable default event handlers. * **children** (`ReactNode`) - Optional - Child elements. ### Icon Options When customizing marker appearance with `icon`: ```typescript { iconUrl?: string, iconRetinaUrl?: string, iconSize?: [width, height], iconAnchor?: [x, y], popupAnchor?: [x, y], shadowUrl?: string, shadowSize?: [width, height], shadowAnchor?: [x, y], className?: string } ``` ### Usage Examples #### Default Marker ```python import dash_leaflet as dl dl.MapContainer( center=[45.5236, -122.6750], zoom=13, children=[ dl.TileLayer(), dl.Marker(position=[45.5236, -122.6750]) ] ) ``` #### Custom Icon ```python dl.Marker( position=[45.5236, -122.6750], icon={ 'iconUrl': 'https://example.com/custom-icon.png', 'iconSize': [32, 32], 'iconAnchor': [16, 32], 'popupAnchor': [0, -32] } ) ``` #### Draggable Marker ```python dl.Marker( id='draggable-marker', position=[45.5236, -122.6750], draggable=True, riseOnHover=True ) ``` #### Marker with Click Event ```python from dash import callback, Input, Output app.layout = dl.MapContainer( center=[45.5236, -122.6750], zoom=13, children=[ dl.TileLayer(), dl.Marker( id='marker', position=[45.5236, -122.6750] ) ] ) @app.callback( Output('output', 'children'), Input('marker', 'n_clicks') ) def on_marker_click(n_clicks): return f"Marker clicked {n_clicks} times" ``` ``` -------------------------------- ### Create Colorbar with Custom Dimensions Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-colorbar.md This example demonstrates how to customize the dimensions of a colorbar. It sets a specific width and height for the colorbar component, positioning it at the bottom right. ```python dl.Colorbar( min=0, max=100, colorscale=['blue', 'red'], width=30, height=250, position='bottomright' ) ``` -------------------------------- ### Example GeoJSON FeatureCollection with Point and LineString Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/types.md Demonstrates a FeatureCollection containing a Point for a city and a LineString for a route. Note that GeoJSON coordinates are in [longitude, latitude] order. ```python geojson_data = { 'type': 'FeatureCollection', 'features': [ { 'type': 'Feature', 'geometry': { 'type': 'Point', 'coordinates': [-122.6750, 45.5236] # Note: GeoJSON uses [lon, lat] }, 'properties': { 'name': 'Portland, OR', 'population': 647805 } }, { 'type': 'Feature', 'geometry': { 'type': 'LineString', 'coordinates': [[-122.6750, 45.5236], [-122.7, 45.6]] }, 'properties': { 'name': 'Route 1' } } ] } ``` -------------------------------- ### Create Elevation/Topography Colorbar Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-colorbar.md This example shows how to create a colorbar for elevation data. It includes custom tick values and corresponding text labels to represent different altitude ranges. ```python dl.Colorbar( min=0, max=5000, colorscale=['#1a9850', '#91cf60', '#d9ef8b', '#ffffbf', '#fee08b', '#fc8d59', '#e08214', '#b35806', '#542788'], tickValues=[0, 1000, 2000, 3000, 4000, 5000], tickText=['0m', '1km', '2km', '3km', '4km', '5km'], label='Elevation' ) ``` -------------------------------- ### Dash Leaflet CircleMarker Example Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-vector-features.md Draws a circle with a pixel-based radius, ensuring consistent size across zoom levels. Configure color, fill, and opacity. ```python import dash_leaflet as dl dl.CircleMarker( center=[45.5236, -122.6750], radius=10, # 10 pixels color='blue', fillColor='blue', fillOpacity=0.7 ) ``` -------------------------------- ### Default Component Configurations in Python Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Customize default settings for MapContainer, TileLayer, and Marker components using Python dictionaries. These defaults simplify initial setup. ```python import dash_leaflet as dl # MapContainer defaults map_defaults = { 'crs': 'EPSG3857', # Web Mercator 'trackViewport': True, # Auto-track zoom/center/bounds 'zoomControl': True, # Show zoom buttons 'attributionControl': True # Show attribution } # TileLayer defaults tile_defaults = { 'url': 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 'attribution': '© OpenStreetMap contributors', 'minZoom': 0, 'maxZoom': 28, 'tileSize': 256 } # Marker defaults marker_defaults = { 'draggable': False, 'keyboard': True, 'riseOnHover': False, 'opacity': 1.0 } ``` -------------------------------- ### Stamen Terrain TileLayer Setup Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-layers.md Implements a Stamen Terrain tile layer. Specifies subdomains, min/max zoom levels, and attribution details. Ensure correct attribution is provided as per Stamen's terms. ```python dl.TileLayer( url='https://stamen-tiles-{s}.a.ssl.fastly.net/terrain/{z}/{x}/{y}{r}.png', attribution='Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under ODbL.', subdomains='abcd', minZoom=0, maxZoom=18 ) ``` -------------------------------- ### Programmatically Control Map Viewport Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-map-container.md This example shows how to programmatically change the map's viewport (center, zoom, and animation) using a Dash callback. It's triggered by a button click and includes animation options. ```python from dash import callback, Input, Output import dash_leaflet as dl # Callback to update viewport when button is clicked @app.callback( Output('map', 'viewport'), Input('zoom-button', 'n_clicks'), prevent_initial_call=True ) def on_zoom(n_clicks): return { 'center': [45.5236, -122.6750], 'zoom': 15, 'transition': 'flyTo', 'options': {'duration': 1} # 1 second animation } ``` -------------------------------- ### Popup with Dynamic Content via Callback Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-overlays.md Updates popup content dynamically based on user interaction, such as clicking on the map. This example uses a Dash callback to display click coordinates. ```python from dash import callback, Input, Output, html @app.callback( Output('popup-content', 'children'), Input('map', 'clickData') ) def update_popup(clickData): if not clickData: return "Click on the map" latlng = clickData['latlng'] return html.Div([ html.P(f"Clicked at: {latlng}") ]) app.layout = dl.MapContainer( id='map', center=[45.5236, -122.6750], zoom=12, children=[ dl.TileLayer(), dl.Popup( id='popup-content', position=[45.5236, -122.6750] ) ] ) ``` -------------------------------- ### Dockerfile for Dash Leaflet Application Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md A Dockerfile to build a containerized Dash Leaflet application. It installs dependencies from requirements.txt and sets the command to run the application with Gunicorn. ```dockerfile FROM python:3.12-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app:server"] ``` -------------------------------- ### Dynamic Map Updates with Callbacks Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/express-utilities.md Dynamically updates a map with GeoJSON data based on user input using Dash callbacks. This example demonstrates fetching data for a selected region and then converting it to GeoJSON. ```python from dash import callback, Input, Output from dash_leaflet.express import dicts_to_geojson @app.callback( Output('map', 'children'), Input('data-selector', 'value') ) def update_map(selected_region): # Fetch data for selected region data = fetch_data_for_region(selected_region) # Convert to GeoJSON geojson = dicts_to_geojson(data, lat='lat', lon='lon') return [ dl.TileLayer(), dl.GeoJSON(data=geojson) ] ``` -------------------------------- ### Using GeoJSON for Dynamic Content Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-groups.md Demonstrates how to use the GeoJSON component for frequently changing data instead of dynamically modifying group children. Includes a callback example to update GeoJSON data. ```python # Instead of dynamically modifying group children app.layout = dl.MapContainer( children=[ dl.TileLayer(), dl.GeoJSON(id='dynamic-geojson', data={...}) ] ) @app.callback( Output('dynamic-geojson', 'data'), Input('filter', 'value') ) def update_geojson(filter_value): # Return filtered GeoJSON return filtered_geojson ``` -------------------------------- ### Sequential Color Scales for Colorbar Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-colorbar.md Provides examples of sequential color scales, which represent a single hue progression from light to dark. These are suitable for data that ranges from low to high values. ```python # Blues (light to dark) colorscale=['#f7fbff', '#deebf7', '#c6dbef', '#9ecae1', '#6baed6', '#4292c6', '#2171b5', '#08519c', '#08306b'] ``` ```python # Reds colorscale=['#fff5f0', '#fee0d2', '#fcbba1', '#fc9272', '#fb6a4a', '#ef3b2c', '#cb181d', '#99000d'] ``` ```python # Greens colorscale=['#f7fcf5', '#e5f5e0', '#c7e9c0', '#a1d99b', '#74c476', '#41ab5d', '#238b45', '#005a32'] ``` -------------------------------- ### Check Installed Dash Leaflet Version Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Retrieve the currently installed version of the dash-leaflet library. This is useful for verifying installation and checking compatibility. ```python import dash_leaflet print(dash_leaflet.__version__) ``` -------------------------------- ### Basic Map Initialization Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/README.md Create a basic map with a tile layer. Set the center, zoom level, and container style. ```python from dash import Dash import dash_leaflet as dl app = Dash() app.layout = dl.MapContainer( center=[45.5236, -122.6750], zoom=12, children=[dl.TileLayer()], style={'height': '100vh'} ) ``` -------------------------------- ### Secure API Key Management in Python Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Demonstrates how to securely load API keys using environment variables instead of hardcoding them. This is crucial for preventing accidental exposure of sensitive credentials. ```python # Bad - do not commit mapbox_token = 'pk_live_...' # Good - use environment variables import os mapbox_token = os.getenv('MAPBOX_ACCESS_TOKEN') ``` -------------------------------- ### Create and Use Custom Panes Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-overlays.md Demonstrates creating two custom panes, 'background' and 'foreground', with different z-index styles to control the stacking order of a Rectangle and a Marker respectively. The 'pane' property of the child components must be set to the name of the custom pane. ```python import dash_leaflet as dl from dash import html dl.MapContainer( center=[45.5236, -122.6750], zoom=12, children=[ dl.TileLayer(), # Custom pane for background overlays dl.Pane( name='background', style={'zIndex': 100}, children=[ dl.Rectangle( bounds=[[45.4, -122.8], [45.6, -122.5]], color='blue', fillOpacity=0.1, pane='background' ) ] ), # Custom pane for foreground elements dl.Pane( name='foreground', style={'zIndex': 500}, children=[ dl.Marker(position=[45.5236, -122.6750], pane='foreground') ] ) ] ) ``` -------------------------------- ### Build and Run Docker Container Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Builds a Docker image for the Dash Leaflet application and runs it, exposing port 8000. ```bash docker build -t dash-leaflet-app . docker run -p 8000:8000 dash-leaflet-app ``` -------------------------------- ### Importing Dash Leaflet Express Utilities Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/INDEX.md Demonstrates how to import utility functions from the dash_leaflet.express module, such as those for colorbars and GeoJSON conversion. ```python from dash_leaflet.express import ( categorical_colorbar, dicts_to_geojson, geojson_to_geobuf ) ``` -------------------------------- ### Marker Click Event Handling Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-vector-features.md Demonstrates how to capture click events on a marker and update a Dash output component. Requires setting up a callback to listen for the 'n_clicks' property. ```python from dash import callback, Input, Output app.layout = dl.MapContainer( center=[45.5236, -122.6750], zoom=13, children=[ dl.TileLayer(), dl.Marker( id='marker', position=[45.5236, -122.6750] ) ] ) @app.callback( Output('output', 'children'), Input('marker', 'n_clicks') ) def on_marker_click(n_clicks): return f"Marker clicked {n_clicks} times" ``` -------------------------------- ### GeoJSON Data Structure Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/INDEX.md Example structure for GeoJSON data, a standard geographic data format. ```json { "type": "FeatureCollection", "features": [{ "type": "Feature", "geometry": {"type": "Point", "coordinates": [lon, lat]}, "properties": {...} }] } ``` -------------------------------- ### Dash Leaflet AttributionControl Example Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-controls.md Use AttributionControl to display layer attribution text. You can customize the position and prefix text. ```python dl.AttributionControl( position='bottomright', prefix='Map created with Dash Leaflet' ) ``` -------------------------------- ### Common GeoJSON Options Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-layers.md Provides examples of common Leaflet GeoJSON options that can be passed to the component for styling and custom behavior. ```python { 'style': {'color': 'blue', 'weight': 2, 'opacity': 0.7}, 'pointToLayer': '/* JS function */', // Custom marker creation 'onEachFeature': '/* JS function */', # Feature-by-feature callback 'filter': '/* JS function */', # Feature filtering 'coordsToLatLng': '/* JS function */' # Coordinate transformation } ``` -------------------------------- ### Upgrade Dash Leaflet using pip Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Install the latest version of dash-leaflet using pip. It is recommended to back up your code before upgrading. ```bash # Back up your code git commit -m "Before upgrading to dash-leaflet 1.x" # Install new version pip install --upgrade dash-leaflet==1.1.3 # Update imports if needed # Most imports remain the same ``` -------------------------------- ### Force Reinstall Dash Leaflet Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Uninstalls and then reinstalls dash-leaflet with the --force-reinstall flag. This can resolve issues related to corrupted installations. ```bash pip uninstall dash-leaflet pip install dash-leaflet --force-reinstall ``` -------------------------------- ### Draw a Circle on a Map Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-vector-features.md Example of using the Circle component within a Dash Leaflet MapContainer. Specifies the center, radius, and fill colors. ```python import dash_leaflet as dl dl.MapContainer( center=[45.5236, -122.6750], zoom=13, children=[ dl.TileLayer(), dl.Circle( center=[45.5236, -122.6750], radius=500, # 500 meters color='red', fillColor='red', fillOpacity=0.3 ) ] ) ``` -------------------------------- ### GeoBuf Compression Error Message Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/express-utilities.md This error message indicates that the required GeoBuf dependencies are missing. Follow the provided installation instructions to resolve the issue. ```text ERROR: Unable to import [geobuf/protobuf]. Please install it, e.g. via pip by running 'pip install dash-leaflet[geobuf]' or 'pip install dash-leaflet[all]'. ``` -------------------------------- ### Convert DataFrame Rows to GeoJSON Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/express-utilities.md Converts rows from a Pandas DataFrame into a GeoJSON FeatureCollection. Requires the pandas library to be installed and the DataFrame to be structured correctly. ```python import pandas as pd from dash_leaflet.express import dicts_to_geojson # Convert DataFrame to GeoJSON df = pd.read_csv('locations.csv') records = df[['latitude', 'longitude', 'name', 'value']].to_dict(orient='records') geojson = dicts_to_geojson(records, lat='latitude', lon='longitude') ``` -------------------------------- ### Dash Leaflet Simple Polyline Example Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-vector-features.md Draws a single line connecting a series of geographic points. Customize line color, weight, and opacity. ```python import dash_leaflet as dl dl.Polyline( positions=[ [45.5, -122.6], [45.6, -122.7], [45.7, -122.8] ], color='blue', weight=5, opacity=0.8 ) ``` -------------------------------- ### CORS Considerations for Tile Providers Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Offers guidance on troubleshooting Cross-Origin Resource Sharing (CORS) errors with tile providers. It suggests checking provider documentation, browser console, and using a proxy if necessary. ```python # Most tile providers work without CORS issues # If you encounter CORS errors, check: # 1. Tile provider documentation # 2. Browser console for specific errors # 3. Proxy through your own server if needed ``` -------------------------------- ### Check Dash Leaflet Version Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Use this Python snippet to verify the installed versions of Dash Leaflet, Dash, and Python. This is useful for debugging compatibility issues. ```python import dash_leaflet import dash import leaflet print(f"Dash Leaflet: {dash_leaflet.__version__}") print(f"Dash: {dash.__version__}") print(f"Python: {platform.python_version()}") ``` -------------------------------- ### Setting Environment Variables for API Keys Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/installation-configuration.md Demonstrates how to set the MAPBOX_ACCESS_TOKEN environment variable for different operating systems and within a Python script. ```bash export MAPBOX_ACCESS_TOKEN='your_token_here' python app.py ``` ```cmd set MAPBOX_ACCESS_TOKEN=your_token_here python app.py ``` ```powershell $env:MAPBOX_ACCESS_TOKEN='your_token_here' python app.py ``` ```python import os os.environ['MAPBOX_ACCESS_TOKEN'] = 'your_token_here' ``` -------------------------------- ### Implement Keyboard Shortcuts Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/events-and-callbacks.md Callback to handle specific keyboard shortcuts (e.g., Escape, Ctrl+Z, Shift+S) when pressed on the map. Returns a descriptive string or None if no shortcut is matched. ```python @app.callback( Output('output', 'children'), Input('map', 'keydownData') ) def handle_shortcuts(keydownData): if not keydownData: return key = keydownData['key'] ctrl = keydownData['ctrlKey'] shift = keydownData['shiftKey'] if key == 'Escape': return "Escape pressed" elif ctrl and key == 'z': return "Ctrl+Z: Undo" elif shift and key == 's': return "Shift+S: Save" return None ``` -------------------------------- ### Combine LayerGroup with LayersControl Source: https://github.com/emilhe/dash-leaflet/blob/master/_autodocs/api-groups.md Integrate LayerGroup with Dash Leaflet's LayersControl to manage overlay visibility. This example shows how to include a LayerGroup as an overlay option. ```python from dash_leaflet import LayersControl, Overlay app.layout = dl.MapContainer( children=[ dl.LayersControl( children=[ # Base layer dl.BaseLayer( dl.TileLayer(), name='Street Map', checked=True ), # Overlay organized with LayerGroup dl.Overlay( dl.LayerGroup( children=[ dl.Polyline(...), dl.Polyline(...), dl.Marker(...) ] ), name='Transportation', checked=True ) ] ) ] ) ```