ipyleaflet Documentation

repository·master·Indexed 23 days ago

https://github.com/jupyter-widgets/ipyleaflet

A bridge between Jupyter and Leaflet that allows developers to create and interact with complex, interactive maps directly within Jupyter notebooks using Python. It consists of the jupyter-leaflet front-end npm package and the ipyleaflet Python backend. Key capabilities include GeoJSON visualization, basemap switching, splitmap controls, Choropleth layers, and various map controls such as GeomanDrawControl, MeasureControl, SearchControl, and LayersControl.

Tokens
60.4K
Snippets
159
Records
272
Agent score
81%

What's inside ipyleaflet

  1. Overview of ipyleaflet capabilities

    master

    ipyleaflet is a Jupyter/Leaflet bridge that enables interactive maps within Jupyter notebooks. It consists of two main parts:

    • jupyter-leaflet: The front-end npm package (the widget component).
    • ipyleaflet: The Python package that serves as the backend for the Python Jupyter kernel.

    Key features include:

    • Selecting and switching between different basemaps.
    • Loading and visualizing GeoJSON data.
    • Using LeafletJS primitives directly.
    • Implementing splitmap controls.
    • Visualizing velocity data on maps.
    • Creating Choropleth layers.
    • Using widget controls within the map interface.
  2. Introduction to ipyleaflet

    master
    ipyleaflet is a Jupyter widget for Leaflet.js that enables interactive maps within Jupyter notebooks. Every object in the library—including Map, TileLayers, Layers, and Controls—is interactive. This means you can dynamically update attributes from either Python code or directly from the browser, and the changes will synchronize.
  3. How interactivity works in ipyleaflet

    master

    Everything in ipyleaflet—including the Map class, Layer classes, and Control classes—is an interactive widget. This means any attribute exposed by these classes can be synchronized between the JavaScript frontend and the Python backend. Common examples of interactive attributes include:

    • map.zoom for controlling map magnification.
    • layer.url for updating tile or data sources.
    • marker.location for moving markers.
    • heatmap.locations for updating heatmap data.
  4. Implement the layer-like interface for custom objects

    master
    The ipyleaflet.Map.add method supports any object that implements a as_leaflet_layer method. This allows downstream developers to create custom data classes or complex objects that can be passed directly to a Map instance. To implement this, your object's as_leaflet_layer method must return an ipyleaflet layer type (such as Heatmap, TileLayer, etc.) that is compatible with the Map object.
  5. Format GeoJSON and choro_data for Choropleth layers

    master

    For a Choropleth layer to render correctly, your data must follow these structures:

    GeoJSON (geo_data) structure: The GeoJSON must contain features with identifiers that match your data dictionary. These identifiers can be found in the id field or within the properties object.

    {
        "type": "FeatureCollection",
        "features": [{
            "type": "Feature",
            "id": "AL",
            "properties": {"name": "Alabama"},
            "geometry": {
                "type": "Polygon",
                "coordinates": [[[-87.359296, 35.00118]]] 
            }
        }]
    }

    Data Dictionary (choro_data) structure: A simple dictionary mapping the identifier (from the GeoJSON) to a float value.

    {'AL': 7.1, 'AK': 6.8}
  6. Use LayersControl to manage layer visibility

    master

    The LayersControl widget adds a layer selector to the map, allowing users to toggle the visibility of different layers.

    To ensure a layer appears in the selector, you must provide a name attribute to the layer (e.g., Marker(name='my_marker')). This name is what the user sees in the control interface. You can specify the position of the control on the map using the position argument (e.g., 'topright').

    from ipyleaflet import Map, Marker, LayersControl
    
    m = Map(center=(50, 0), zoom=5)
    
    # Layers must have a 'name' to appear in the LayersControl
    marker1 = Marker(name='marker1', location=(48, -2))
    marker2 = Marker(name='marker2', location=(50, 0))
    marker3 = Marker(name='marker3', location=(52, 2))
    
    m.add(marker1)
    m.add(marker2)
    m.add(marker3)
    
    # Add the control to the map
    control = LayersControl(position='topright')
    m.add(control)
    
    m
  7. Create a TileLayer using basemaps

    master

    You can create a TileLayer instance easily using the basemap_to_tiles function. This function accepts a basemap object from the basemaps dictionary (e.g., basemaps.CartoDB.DarkMatter).

    For certain providers like NASA GIBS, you can also specify a date string to load specific imagery.

    from ipyleaflet import Map, basemaps, basemap_to_tiles
    
    m = Map(center=(52.204793, 360.121558), zoom=9)
    
    # Create a layer from a basemap
    dark_matter_layer = basemap_to_tiles(basemaps.CartoDB.DarkMatter)
    m.add(dark_matter_layer)
    
    # Example with a specific date for NASA imagery
    nasa_layer = basemap_to_tiles(basemaps.NASAGIBS.ModisTerraTrueColorCR, "2018-04-08")
    m.add(nasa_layer)
  8. Manage multiple layers using LayerGroup

    master

    A LayerGroup allows you to group multiple layers together and manage them as a single unit. You can add or remove individual layers from the group dynamically, which in turn updates the map. This is useful for toggling visibility of related features or organizing complex map compositions.

    To use a LayerGroup:

    1. Create your individual layers (e.g., Marker, Circle, Rectangle).
    2. Initialize a LayerGroup with a tuple of layers passed to the layers argument.
    3. Add the LayerGroup to your Map instance using m.add(layer_group).
    4. Use .add_layer(layer) or .remove_layer(layer) to modify the group's contents.
    from ipyleaflet import Map, basemap_to_tiles, basemaps, Marker, Circle, Rectangle, LayerGroup
    
    toner = basemap_to_tiles(basemaps.Stadia.StamenTerrain)
    m = Map(layers=(toner, ), center=(50, 354), zoom=5)
    
    # Create some layers
    marker = Marker(location=(50, 354))
    circle = Circle(location=(50, 370), radius=50000, color="yellow", fill_color="yellow")
    rectangle = Rectangle(bounds=((54, 354), (55, 360)), color="orange", fill_color="orange")
    
    # Create layer group
    layer_group = LayerGroup(layers=(marker, circle))
    
    m.add(layer_group)
    
    # Dynamically modify the group
    layer_group.add_layer(rectangle)
    layer_group.remove_layer(circle)
  9. Add layers and controls to a Map

    master

    The Map object allows you to add layers (like Marker) and controls using the .add() method. Because all layers and controls are themselves widgets, you can dynamically update their attributes from Python or through direct interaction on the map interface.

    from ipyleaflet import Map, Marker, basemaps, basemap_to_tiles
    
    m = Map(
        basemap=basemap_to_tiles(basemaps.NASAGIBS.ModisTerraTrueColorCR, "2017-04-08"),
        center=(52.204793, 360.121558),
        zoom=4
    )
    
    m.add(Marker(location=(52.204793, 360.121558)))
    
    m
  10. Visualize WKT data with WKTLayer

    master

    The WKTLayer class in ipyleaflet allows you to visualize geometries represented in Well-known Text (WKT) format on a Map. You can load WKT data in two ways:

    1. From a file: Provide a file path to the .wkt file using the path argument.
    2. From a string: Provide the WKT geometry directly using the wkt_string argument.

    You can customize the appearance of the layer during interaction using the hover_style dictionary (e.g., changing the fillColor).

    from ipyleaflet import Map, WKTLayer
    
    # Option 1: Load from a file
    m = Map(center=(42.3152960829043, -71.1031627617667), zoom=17)
    wlayer = WKTLayer(path="test.wkt", hover_style={"fillColor": "red"})
    m.add(wlayer)
    
    # Option 2: Load from a WKT string
    m = Map(center=(-25.0927734375, 10.689697265625), zoom=4)
    wlayer = WKTLayer(
        wkt_string="POLYGON((10.689697265625 -25.0927734375, 34.595947265625 -20.1708984375, 38.814697265625 -35.6396484375, 13.502197265625 -39.1552734375, 10.689697265625 -25.0927734375))",
        hover_style={"fillColor": "red"},
    )
    m.add(wlayer)
  11. Configure multiple basemaps for LayersControl switching

    master

    To enable built-in basemap switching using the LayersControl widget, you must:

    1. Create TileLayer objects using basemap_to_tiles.
    2. Set the .base attribute of each layer to True.
    3. Pass these layers as a list to the layers argument of the Map constructor.
    4. Add a LayersControl() instance to the map.
    from ipyleaflet import Map, basemaps, basemap_to_tiles, LayersControl
    
    mapnik = basemap_to_tiles(basemaps.OpenStreetMap.Mapnik)
    mapnik.base = True
    
    toner = basemap_to_tiles(basemaps.Stadia.StamenTerrain)
    toner.base = True
    
    # Pass the base layers to the Map constructor
    m = Map(layers=[mapnik, toner], center=(52.204793, 360.121558), zoom=9)
    
    # Add the control to allow switching
    m.add(LayersControl())
  12. Select a basemap for an ipyleaflet Map

    master

    You can set the background map of an ipyleaflet.Map instance using the basemap argument. The available default basemaps are provided via the basemaps module. These basemaps are sourced from the xyzservices package.

    If a specific provider is not available in the basemaps module, you can use a custom TileLayer to provide your own tiles.

    from ipyleaflet import Map, basemaps
    
    center = [38.128, 2.588]
    zoom = 5
    
    # Example using OpenStreetMap Mapnik
    Map(basemap=basemaps.OpenStreetMap.Mapnik, center=center, zoom=zoom)