Dash Leaflet

repository·master·Indexed 42 days ago

https://github.com/emilhe/dash-leaflet

A lightweight Python wrapper around React-Leaflet for integrating interactive map components into Dash applications. Version 1.1.3 provides a comprehensive set of components including MapContainer, TileLayer, GeoJSON, and various vector shapes, controls, and overlays. It includes utility functions like categorical_colorbar, dicts_to_geojson, and geojson_to_geobuf for spatial data processing.

Tokens
11.3K
Snippets
35
Records
50
Agent score
53%

What's inside Dash Leaflet

  1. Quickstart: Create a basic Leaflet map

    master

    After installation, you can initialize a basic map by using dl.Map and adding a dl.TileLayer. The dl.Map component accepts center (coordinates), zoom, and a style dictionary for CSS properties like height.

    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()
  2. Build Dash Leaflet from source

    master

    To build the project from the repository, ensure you have Python 3.12 and uv installed. Follow these steps:

    1. Clone the repository and enter the directory.
    2. Create a virtual environment and sync Python dependencies using uv.
    3. Install npm packages (using --ignore-scripts) and run the build script.
    git clone git@github.com:thedirtyfew/dash-leaflet.git
    cd dash-leaflet
    
    uv venv && source .venv/bin/activate && uv sync
    
    npm i --ignore-scripts
    npm run build
  3. Understand event data structures in Dash Leaflet

    master

    Dash Leaflet provides specific data structures for different event types. These are used to populate event handler data in Dash callbacks.

    Click Events (SingleClickEvent & DoubleClickEvent)

    • n_clicks / n_dblclicks: Integer representing the number of times the event fired.
    • clickData / dblclickData: Object containing:
      • latlng: number[] (Latitude and Longitude)
      • layerPoint: number[]
      • containerPoint: number[]

    Keyboard Events (KeyboardEvents)

    • n_keydowns: Integer representing the number of key presses.
    • keydownData: Object containing:
      • key: string
      • ctrlKey: boolean
      • metaKey: boolean
      • shiftKey: boolean
      • repeat: boolean

    Load Events (LoadEvents)

    • n_loads: Integer representing the number of times the load event has fired.
  4. Enable Marker Clustering in GeoJSON

    master

    By setting cluster={true}, the component uses supercluster to group points into clusters.

    Key clustering props:

    • clusterToLayer: Function to determine how a cluster is drawn. Receives (feature, latlng, index).
    • spiderfyOnMaxZoom: If true, markers that cannot be resolved at the maximum zoom level will 'spiderfy' (expand outwards) on click.
    • superClusterOptions: Pass configuration options directly to the underlying supercluster library.

    Note: When clustering is enabled, the component automatically manages the lifecycle of cluster markers and handles map movement to redraw clusters dynamically.

    <GeoJSON
      data={pointsData}
      cluster={true}
      spiderfyOnMaxZoom={true}
      superClusterOptions={{ maxZoom: 12, radius: 40 }}
      clusterToLayer={(feature, latlng) => L.marker(latlng, { icon: myCustomIcon })}
    />
  5. How Colorbar handles discrete vs continuous scales

    master

    The Colorbar component can render either a continuous gradient or a discrete set of color classes based on the classes property:

    1. Continuous (Default): If classes is not provided (or is null), the component creates a smooth gradient using chroma.scale(colorscale).domain([min, max]).
    2. Discrete: If classes is provided as a number or an array of numbers, the component creates a stepped scale using chroma.scale(colorscale).domain([min, max]).classes(classes).

    This allows you to switch between a smooth color transition and a categorized color legend.

  6. Define custom Dash component props

    master

    When creating custom components or extending existing ones, it is recommended to use TypeScript type instead of interface. This allows you to define the order of props using type concatenation with DashComponentProps.

    type Props = {
        my_prop: string;
    } & DashComponentProps;
  7. Configure Popup and Tooltip properties

    master

    Use PopupProps or TooltipProps to control information overlays.

    PopupProps highlights:

    • content: HTML content or string.
    • autoClose: If false, prevents closing when another popup opens.
    • closeButton: Controls visibility of the close button.
    • maxWidth / minWidth / maxHeight: Dimensions of the popup.
    • autoPan: Whether the map pans to fit the popup.

    TooltipProps highlights:

    • direction: Where to open (right, left, top, bottom, center, or auto).
    • permanent: If true, the tooltip stays open.
    • sticky: If true, the tooltip follows the mouse.
  8. Configure the Colorbar component

    master

    The Colorbar component is a Leaflet control used to display a color scale, typically for representing data ranges visually on a map. It leverages chroma-js for color scale generation. You can customize the scale, dimensions, ticks, and appearance via ColorbarProps.

    // Example usage of ColorbarProps
    const colorbarProps = {
        colorscale: 'Viridis', // or a list of colors like ['black', '#fdd49e', 'red']
        width: 100,
        height: 10,
        min: 0,
        max: 1,
        classes: 5, // Use for discrete classes; if null, it is continuous
        unit: 'm/s',
        nTicks: 5,
        tickDecimals: 2,
        tooltip: true,
        opacity: 0.8,
        style: { fontSize: '12px' },
        className: 'my-custom-colorbar'
    };
  9. Configure Map Controls

    master

    Controls are UI elements added to the map interface.

    LayersControl:

    • collapsed: If true, the control is collapsed into an icon and expands on hover/touch.
    • position: Map control position (e.g., topright).

    BaseLayer and Overlay Props (for LayersControl):

    • name: The label used in the LayersControl UI.
    • checked: If true, the layer is shown by default.

    Other Controls:

    • ZoomControl, AttributionControl, and ScaleControl all support the position property to define where they appear on the map.
  10. Import Dash Leaflet components

    master

    The dash-leaflet TypeScript library exports a comprehensive set of components for building interactive maps. These components correspond to Leaflet layers, controls, and overlays. You can import them directly from the main entrypoint to use within your Dash application components.

    import {
        MapContainer,
        TileLayer,
        Marker,
        Popup,
        Circle,
        Polyline,
        Polygon,
        GeoJSON
    } from 'dash-leaflet';
  11. Use EditControl to enable drawing and editing features

    master

    The EditControl component provides a user interface for drawing new shapes (markers, polygons, etc.) and editing existing layers on a Leaflet map using the leaflet-draw plugin. It integrates with the map's layer container to manage drawn elements.

    Key Properties

    • draw: An object to configure drawing controls (refer to Leaflet.draw documentation for valid options).
    • edit: An object to configure editing controls.
    • drawToolbar: Used to programmatically manipulate the drawing toolbar. You can change the active mode or trigger an action.
    • editToolbar: Used to programmatically manipulate the editing toolbar. You can change the active mode or trigger an action.
    • action: An object that fires on every action, providing details about the layer_type, the type of action, and the number of n_actions performed.
    • eventHandlers: Standard Leaflet event handlers to listen for drawing and editing events.
    // Example usage of EditControl
    <EditControl
        draw={{
            polyline: { shapeOptions: { color: 'red' } }
        }}
        edit={true}
        drawToolbar={{
            mode: 'polygon',
            action: 'cancel',
            n_clicks: 1
        }}
        eventHandlers={{
            'draw:created': (e) => console.log('Layer created:', e),
        }}
    />