### Install Dependencies with uv Source: https://github.com/developmentseed/lonboard/blob/main/examples/migration.ipynb Install uv and launch the notebook using uvx. This command is included when installing uv. ```bash uvx juv run examples/migration.ipynb ``` -------------------------------- ### Install Dependencies with uvx Source: https://github.com/developmentseed/lonboard/blob/main/examples/data-filter-extension.ipynb Install required dependencies using uvx and launch the notebook. Ensure uv is installed first. ```bash uvx juv run examples/data-filter-extension.ipynb ``` -------------------------------- ### Install Dependencies with uvx Source: https://github.com/developmentseed/lonboard/blob/main/examples/clicked-point.ipynb Install dependencies using uvx and launch the notebook. The `uvx` command is included when installing `uv`. ```bash uvx juv run examples/clicked-point.ipynb ``` -------------------------------- ### Run Example Notebook with Local lonboard Source: https://github.com/developmentseed/lonboard/blob/main/DEVELOP.md Run an example notebook using a local version of lonboard. Ensure the JavaScript bundle is built first and use the --with flag for local path. ```bash ANYWIDGET_HMR=1 uvx juv run --with="../" examples/air-traffic-control.ipynb ``` -------------------------------- ### Lonboard CLI Usage Example Source: https://github.com/developmentseed/lonboard/blob/main/docs/cli.md An example of how to use the Lonboard CLI to visualize a local GeoJSON file. ```bash lonboard data.geojson ``` -------------------------------- ### Install and Load DuckDB Spatial Extension Source: https://github.com/developmentseed/lonboard/blob/main/examples/duckdb.ipynb Connect to DuckDB and install/load the spatial extension. Ensure DuckDB is installed with the spatial extension available. ```python import duckdb from lonboard import HeatmapLayer, Map con = duckdb.connect() duckdb.install_extension("spatial", connection=con) duckdb.load_extension("spatial", connection=con) ``` -------------------------------- ### Install Lonboard with Pip Source: https://github.com/developmentseed/lonboard/blob/main/README.md Use this command to install Lonboard using pip. ```bash pip install lonboard ``` -------------------------------- ### Install Dependencies Source: https://github.com/developmentseed/lonboard/blob/main/examples/integrations/sidecar.ipynb Install necessary libraries for data manipulation and visualization. Restart Jupyter and refresh your browser tab after installation if needed. ```bash pip install sidecar pyogrio ``` -------------------------------- ### Import necessary libraries Source: https://github.com/developmentseed/lonboard/blob/main/examples/data-filter-extension-categorical.ipynb Imports all required libraries for the example, including geodatasets, geopandas, traitlets, ipywidgets, palettable, and lonboard components. ```python import geodatasets import geopandas import traitlets from ipywidgets import Button, HBox, SelectMultiple, VBox from palettable.colorbrewer.diverging import RdYlGn_11 import lonboard from lonboard import Map, ScatterplotLayer from lonboard.layer_extension import DataFilterExtension ``` -------------------------------- ### Install JavaScript Module Dependencies Source: https://github.com/developmentseed/lonboard/blob/main/DEVELOP.md Install all necessary module dependencies for the JavaScript component of the project using pnpm. ```bash pnpm install ``` -------------------------------- ### Initialize AzureStore for Overture Data (Commented Out) Source: https://github.com/developmentseed/lonboard/blob/main/examples/overture-geoparquet.ipynb An alternative to S3Store, this commented-out example shows how to initialize an AzureStore to access Overture data from Azure Blob Storage. The subsequent steps would remain the same. ```python # from obstore.store import AzureStore # store = AzureStore.from_url( # "https://overturemapswestus2.blob.core.windows.net/release", # skip_signature=True, # ) ``` -------------------------------- ### JavaScript Accessor Expansion Example Source: https://github.com/developmentseed/lonboard/blob/main/docs/how-it-works/internals.md Shows how the Pydeck DSL accessor is expanded into a JavaScript function for data retrieval. ```javascript getRadius: (object) => object.properties.valuePerSqm ``` -------------------------------- ### Install Playwright Browser Source: https://github.com/developmentseed/lonboard/blob/main/tests/ui/README.md Installs the Chromium browser for Playwright. This is a prerequisite for running browser-based UI tests. ```bash uv run playwright install chromium ``` -------------------------------- ### Install Lonboard with Conda Source: https://github.com/developmentseed/lonboard/blob/main/README.md Use this command to install Lonboard from the conda-forge channel. ```bash conda install -c conda-forge lonboard ``` -------------------------------- ### Pydeck Accessor Example Source: https://github.com/developmentseed/lonboard/blob/main/docs/how-it-works/internals.md Illustrates the Pydeck syntax for defining accessors, which requires learning a Domain-Specific Language (DSL) for computed properties. ```python getRadius="@@=properties.valuePerSqm" ``` -------------------------------- ### Watch for JavaScript Changes and Rebuild Source: https://github.com/developmentseed/lonboard/blob/main/DEVELOP.md Start a watch process that rebuilds the JavaScript bundle automatically when changes are detected in the /src folder. ```bash pnpm build:watch ``` -------------------------------- ### Import necessary libraries Source: https://github.com/developmentseed/lonboard/blob/main/examples/kontur_pop.ipynb Imports required libraries for data manipulation, visualization, and map display. Ensure these libraries are installed. ```python import warnings import geopandas as gpd from matplotlib.colors import LogNorm from palettable.colorbrewer.diverging import BrBG_10 from sidecar import Sidecar from lonboard import H3HexagonLayer, Map from lonboard.colormap import apply_continuous_cmap ``` -------------------------------- ### Import Libraries for Data Visualization Source: https://github.com/developmentseed/lonboard/blob/main/examples/internet-speeds.ipynb Imports necessary libraries for data manipulation, geospatial analysis, and interactive mapping with Lonboard. Ensure these libraries are installed before running. ```python from pathlib import Path import geopandas as gpd import pandas as pd import shapely from palettable.colorbrewer.diverging import BrBG_10 from sidecar import Sidecar from lonboard import Map, ScatterplotLayer from lonboard.colormap import apply_continuous_cmap ``` -------------------------------- ### Register Python Environment with JupyterLab Source: https://github.com/developmentseed/lonboard/blob/main/DEVELOP.md Register the current uv-managed Python environment with JupyterLab to use lonboard in notebooks. Ensure uv is installed. ```bash uv run python -m ipykernel install --user --name "lonboard" ``` -------------------------------- ### Create a Reactive Map in Shiny Source: https://github.com/developmentseed/lonboard/blob/main/docs/ecosystem/shiny.md This example demonstrates how to create a reactive map in a Shiny application. It includes setting up a color selection input and rendering a Lonboard map with a scatterplot layer. The fill color of the scatterplot layer is updated reactively based on user input. ```python import geopandas as gpd from shiny import reactive from shiny.express import input, ui from shinywidgets import render_widget from lonboard import Map, ScatterplotLayer colors = { "Red": [200, 0, 0], "Green": [0, 200, 0], "Blue": [0, 0, 200], } ui.input_select("color_select", "Color", choices=list(colors.keys())) @render_widget def map(): gdf = gpd.read_file(gpd.datasets.get_path("naturalearth_cities")) layer = ScatterplotLayer.from_geopandas(gdf, radius_min_pixels=2) return Map(layer) @reactive.effect def set_fill_color(): map.widget.layers[0].get_fill_color = colors[input.color_select()] ``` -------------------------------- ### Import necessary libraries Source: https://github.com/developmentseed/lonboard/blob/main/examples/column-layer.ipynb Imports GeoPandas for data manipulation and ColumnLayer and Map from Lonboard for visualization. Ensure these libraries are installed. ```python import geopandas as gpd from lonboard import ColumnLayer, Map ``` -------------------------------- ### Load Geospatial Data with Arrow Backend using pyogrio Source: https://github.com/developmentseed/lonboard/blob/main/docs/performance.md Use this when reading geospatial files to load data directly into Arrow-based columns, avoiding conversion overhead. Ensure pyogrio version 0.7 or later is installed. ```python import pyogrio import pandas as pd arrow_to_pandas_kwargs = { 'types_mapper': lambda pa_dtype: pd.ArrowDtype(pa_dtype) } gdf = pyogrio.read_dataframe( "path/to/file", use_arrow=True, arrow_to_pandas_kwargs=arrow_to_pandas_kwargs ) ``` -------------------------------- ### Import necessary libraries for Marimo and DataFusion Source: https://github.com/developmentseed/lonboard/blob/main/examples/marimo/nyc_taxi_trips.md Imports essential libraries for data manipulation, geospatial operations, and visualization within a Marimo environment. Ensure these libraries are installed before running. ```python from pathlib import Path import marimo as mo import requests from arro3.core import Table from datafusion import SessionContext from geodatafusion import register_all from matplotlib.colors import Normalize from palettable.colorbrewer.diverging import BrBG_10 from tqdm.notebook import tqdm from lonboard import ArcLayer, Map, ScatterplotLayer from lonboard.colormap import apply_continuous_cmap from lonboard.layer_extension import BrushingExtension ``` -------------------------------- ### Avoid Recreating Layers: Bad Example Source: https://github.com/developmentseed/lonboard/blob/main/docs/performance.md Creating a new map object when only rendering options need to change results in the entire GeoDataFrame being sent to the browser twice. ```python map1 = ScatterplotLayer.from_geopandas(my_geodataframe) # Next cell map2 = ScatterplotLayer.from_geopandas( my_geodataframe, get_fill_color=[255, 0, 0] ) ``` -------------------------------- ### Serve MkDocs Documentation Locally Source: https://github.com/developmentseed/lonboard/blob/main/DEVELOP.md Serve the MkDocs documentation website locally for development and preview. This command uses uv to run mkdocs. ```bash uv run --group docs mkdocs serve ``` -------------------------------- ### Initialize S3Store for Lonboard COG Rendering Source: https://github.com/developmentseed/lonboard/blob/main/docs/blog/posts/initial-cog.md Set up an Obstore S3Store to access COG data from an AWS bucket. Ensure the bucket name and region are correctly specified. ```python import io from async_geotiff import GeoTIFF, Tile from async_geotiff.utils import reshape_as_image from obstore.store import S3Store from PIL import Image from lonboard import Map, RasterLayer from lonboard.raster import EncodedImage # Create a new Obstore S3Store mounted to our desired bucket store = S3Store("nz-imagery", region="ap-southeast-2", skip_signature=True) ``` -------------------------------- ### Start JupyterLab with Hot-Reloading Source: https://github.com/developmentseed/lonboard/blob/main/DEVELOP.md Start JupyterLab with hot-reloading enabled for JavaScript code updates. ANYWIDGET_HMR=1 is required for this feature. ```bash ANYWIDGET_HMR=1 uv run --group watchfiles jupyter lab ``` -------------------------------- ### Import necessary libraries Source: https://github.com/developmentseed/lonboard/blob/main/examples/interleaved-labels.ipynb Import `BitmapLayer` and `Map` from lonboard, and `CartoStyle`, `MaplibreBasemap` for basemap integration. ```python from lonboard import BitmapLayer, Map from lonboard.basemap import CartoStyle, MaplibreBasemap ``` -------------------------------- ### Import necessary libraries Source: https://github.com/developmentseed/lonboard/blob/main/examples/raster-pmtiles.ipynb Import PMTilesReader from async-pmtiles, HTTPStore from obstore, and Map and RasterLayer from lonboard. These are essential for creating and displaying raster data from PMTiles. ```python from async_pmtiles import PMTilesReader from obstore.store import HTTPStore from lonboard import Map, RasterLayer ``` -------------------------------- ### Debug render callback with fetched tile Source: https://github.com/developmentseed/lonboard/blob/main/examples/raster-cog-rgb-server.ipynb Demonstrates how to debug the render_rgb_tile function by manually fetching and passing a tile. ```python ``` -------------------------------- ### Get Matplotlib Colormap Source: https://github.com/developmentseed/lonboard/blob/main/examples/north-america-roads.ipynb Access the Matplotlib colormap object from the selected 'palettable' colormap. ```python cmap.mpl_colormap ``` -------------------------------- ### Lonboard CLI Help Source: https://github.com/developmentseed/lonboard/blob/main/docs/cli.md Displays the help message for the Lonboard CLI, outlining available options and usage. ```bash lonboard --help ``` -------------------------------- ### Animate the TripsLayer Source: https://github.com/developmentseed/lonboard/blob/main/examples/air-traffic-control.ipynb Starts the animation for the TripsLayer, defining the time step for animation and the frames per second. ```python layer.animate(step=timedelta(minutes=1), fps=50) ``` -------------------------------- ### Initialize S3Store for COG access Source: https://github.com/developmentseed/lonboard/blob/main/examples/raster-cog-rgb-server.ipynb Create an Obstore S3Store instance to access GeoTIFF files from an AWS S3 bucket. Ensure correct region and skip signature if necessary. ```python # Obstore store store = S3Store("sentinel-cogs", region="us-west-2", skip_signature=True) ``` -------------------------------- ### Animate TripsLayer Source: https://github.com/developmentseed/lonboard/blob/main/examples/ais-movingpandas.ipynb Configures and starts the animation for the TripsLayer, defining the time step and frames per second for the animation. ```python trips_layer.animate(step=timedelta(seconds=30), fps=50) ``` -------------------------------- ### Initialize S3Store for Overture Data Source: https://github.com/developmentseed/lonboard/blob/main/examples/overture-geoparquet.ipynb Creates an S3Store instance to access Overture data on AWS S3. Ensure the bucket, region, and prefix are correctly configured for your data. ```python from obstore.store import S3Store store = S3Store( bucket="overturemaps-us-west-2", region="us-west-2", prefix="release", skip_signature=True, ) ``` -------------------------------- ### Serve MkDocs with CI Environment Variable Source: https://github.com/developmentseed/lonboard/blob/main/DEVELOP.md Serve the MkDocs documentation locally with the CI environment variable set, which enables the jupyter-mkdocs plugin. This is useful for inspecting docs with Jupyter notebooks. ```bash CI=true uv run --group docs mkdocs serve ``` -------------------------------- ### Inspect GeoDataFrame with viz Source: https://github.com/developmentseed/lonboard/blob/main/docs/ecosystem/geopandas.md Use the top-level `viz` function for a quick inspection of a GeoPandas GeoDataFrame. Ensure GeoPandas and geodatasets are installed. ```python import geodatasets import geopandas as gpd from lonboard import viz # New York City boroughs gdf = gpd.read_file(geodatasets.get_path('nybb')) viz(gdf) ``` -------------------------------- ### Initialize S3 Store Source: https://github.com/developmentseed/lonboard/blob/main/examples/raster-cog-nlcd-server.ipynb Creates an S3Store instance to access objects in a specified bucket and region. Set skip_signature to True for public buckets. ```python # Obstore store store = S3Store( bucket="ds-deck.gl-raster-public", region="us-east-1", skip_signature=True, ) ``` -------------------------------- ### Debug Render Callback with Fetched Tile Source: https://github.com/developmentseed/lonboard/blob/main/examples/raster-cog-nlcd-server.ipynb Demonstrates how to debug the `render_paletted_tile` function by manually fetching a tile and passing it to the callback. ```python # We can debug our render_paletted_tile function by passing in a tile we fetch ourselves: ``` -------------------------------- ### Create PMTiles reader with HTTPStore Source: https://github.com/developmentseed/lonboard/blob/main/examples/raster-pmtiles.ipynb Instantiate an HTTPStore to access remote data, then use PMTilesReader.open to create a reader for a specified PMTiles file. Obstore supports various storage backends like AWS, GCS, Azure, and local files. ```python store = HTTPStore("https://air.mtn.tw") reader = await PMTilesReader.open("flowers.pmtiles", store=store) ``` -------------------------------- ### Get Total Number of Rows Source: https://github.com/developmentseed/lonboard/blob/main/examples/overture-geoparquet.ipynb Retrieves the total number of rows in the GeoParquet dataset. This provides a count of all features within the dataset. ```python dataset.num_rows ``` -------------------------------- ### Import necessary libraries Source: https://github.com/developmentseed/lonboard/blob/main/examples/clicked-point.ipynb Imports `Tuple` for type hinting, `ipywidgets` for UI elements, and `Map` from `lonboard`. ```python from typing import Tuple import ipywidgets as widgets from lonboard import Map ``` -------------------------------- ### Create and Display Basic Map Source: https://github.com/developmentseed/lonboard/blob/main/examples/north-america-roads.ipynb Create a Lonboard Map object with a PathLayer initialized from the GeoDataFrame and display the map. ```python layer = PathLayer.from_geopandas(gdf, width_min_pixels=0.8) map_ = Map(layer) map_ ``` -------------------------------- ### Get Min and Max Normalized Values Source: https://github.com/developmentseed/lonboard/blob/main/examples/north-america-roads.ipynb Verify the minimum and maximum values of the normalized 'scalerank' array to confirm it spans from 0 to 1. ```python normalized_scale_rank.min(), normalized_scale_rank.max() ``` -------------------------------- ### Get Cyclic Colormap Source: https://github.com/developmentseed/lonboard/blob/main/examples/map_challenge/1-points.ipynb Retrieves the 'twilight' colormap from matplotlib, which is a cyclic colormap suitable for representing cyclical data like time of day. ```python colormap = mpl.colormaps["twilight"] ``` ```python colormap ``` -------------------------------- ### Link Local Development Packages Source: https://github.com/developmentseed/lonboard/blob/main/DEVELOP.md Link local copies of packages, such as deck.gl-raster, for development. Ensure versions are pinned identically in both projects. ```bash pnpm link ../deck.gl-raster/packages/* ``` -------------------------------- ### Initialize and display the Map Source: https://github.com/developmentseed/lonboard/blob/main/examples/column-layer.ipynb Creates a Lonboard Map object with the configured ColumnLayer. The `view_state` parameter sets the initial camera position, including longitude, latitude, zoom level, pitch, and bearing. ```python m = Map( layer, view_state={ "longitude": -100, "latitude": 35, "zoom": 4, "pitch": 45, "bearing": 0, }, ) m ``` -------------------------------- ### Load Road Data from URL Source: https://github.com/developmentseed/lonboard/blob/main/examples/north-america-roads.ipynb Load road data from a specified URL using GeoPandas. This example uses the `pyogrio` engine for faster data loading. ```python url = "https://naciscdn.org/naturalearth/10m/cultural/ne_10m_roads_north_america.zip" ``` ```python gdf = gpd.read_file(url, engine="pyogrio") ``` -------------------------------- ### Get Number of Row Groups Source: https://github.com/developmentseed/lonboard/blob/main/examples/overture-geoparquet.ipynb Retrieves the number of row groups (spatial partitions) within the opened GeoParquet dataset. This indicates the level of spatial partitioning. ```python dataset.num_row_groups ``` -------------------------------- ### Import necessary libraries Source: https://github.com/developmentseed/lonboard/blob/main/examples/integrations/color-picker.ipynb Import lonboard, geopandas, and ipywidgets for map creation and data handling. ```python import geodatasets import geopandas as gpd import ipywidgets from lonboard import Map, SolidPolygonLayer ``` -------------------------------- ### Import necessary libraries Source: https://github.com/developmentseed/lonboard/blob/main/examples/raster-cog-rgb-server.ipynb Import libraries for asynchronous operations, GeoTIFF handling, image encoding, S3 storage, and Lonboard visualization. ```python import io import numpy as np from async_geotiff import GeoTIFF from async_geotiff import Tile as GeoTIFFTile from async_geotiff.utils import reshape_as_image from obstore.store import S3Store from PIL import Image from sidecar import Sidecar from lonboard import Map, RasterLayer from lonboard.raster import EncodedImage ``` -------------------------------- ### Shallow Clone Repository Source: https://github.com/developmentseed/lonboard/blob/main/DEVELOP.md Use a shallow clone to quickly get the repository without the full history, especially useful for development without the gh-pages branch. ```bash git clone --depth 1 https://github.com/developmentseed/lonboard.git ``` -------------------------------- ### Create two Lonboard maps with different basemaps Source: https://github.com/developmentseed/lonboard/blob/main/examples/linked-maps.ipynb Initializes two Lonboard maps with distinct basemaps (Positron and DarkMatter) and specific initial view states. The maps are configured with `flex='1'` layout to display side-by-side in an HBox. ```python ## Create postitron map focused on the arch positron_map = Map( layers=[], basemap_style=CartoBasemap.Positron, view_state={ "longitude": -90.1849, "latitude": 38.6245, "zoom": 16, "pitch": 0, "bearing": 0, }, layout=widgets.Layout(flex="1"), ) ## Create postitron map focused on the lady liberty darkmatter_map = Map( layers=[], basemap_style=CartoBasemap.DarkMatter, view_state={ "longitude": -74.04454, "latitude": 40.6892, "zoom": 16, "pitch": 0, "bearing": 0, }, layout=widgets.Layout(flex="1"), ) maps_box = widgets.HBox([positron_map, darkmatter_map]) maps_box ``` -------------------------------- ### Get Selected Bounding Box from Map Source: https://github.com/developmentseed/lonboard/blob/main/examples/overture-geoparquet.ipynb Retrieves the bounding box coordinates selected by the user on the Lonboard map. This is used to define a spatial subset for data fetching. ```python m.selected_bounds ``` -------------------------------- ### Initialize and Display Map Source: https://github.com/developmentseed/lonboard/blob/main/examples/map_challenge/6-asia.ipynb Initializes a Lonboard Map with the configured river layer and displays it. ```python m = Map(layers=[layer]) m ``` -------------------------------- ### Display Lonboard Map in Panel Source: https://github.com/developmentseed/lonboard/blob/main/docs/ecosystem/panel.md Embed a Lonboard Map into a Panel application using the IPyWidget pane. Ensure 'panel' and 'ipywidgets_bokeh' are installed. The map is configured to fit available space. ```python import geopandas as gpd from lonboard import Map, ScatterplotLayer import panel as pn pn.extension("ipywidgets") @pn.cache def get_data(): return gpd.read_file(r"https://naciscdn.org/naturalearth/110m/cultural/ne_110m_populated_places_simple.zip") gdf = get_data() layer = ScatterplotLayer.from_geopandas(gdf, radius_min_pixels=2, get_fill_color="red") cities_map = Map(layer) # Fit to the available space cities_map.layout.height = cities_map.layout.width = "100%" pn.Column( "# Lonboard Map", pn.pane.IPyWidget(cities_map, height=500, width=1000), ).servable() ``` -------------------------------- ### Create and display the map Source: https://github.com/developmentseed/lonboard/blob/main/examples/air-traffic-control.ipynb Creates a Lonboard Map instance with the configured TripsLayer and sets initial view state parameters like longitude, latitude, zoom, pitch, and bearing. The map height is also increased. ```python m = Map( layer, view_state={ "longitude": -73.8, "latitude": 40.6, "zoom": 9.5, "pitch": 50.6, "bearing": 8.24, }, # Increase height of generated map height=800, ) m ``` -------------------------------- ### Visualize PMTiles Raster Archives with Lonboard Source: https://github.com/developmentseed/lonboard/blob/main/docs/blog/posts/lonboard-0.14.md Use this snippet to visualize raster PMTiles archives over HTTP. Ensure you have `async_pmtiles`, `lonboard`, and `obstore` installed. The `RasterLayer` only supports raster-formatted PMTiles. ```python from async_pmtiles import PMTilesReader from lonboard import Map, RasterLayer from obstore.store import HTTPStore store = HTTPStore("https://air.mtn.tw") reader = await PMTilesReader.open("flowers.pmtiles", store=store) layer = RasterLayer.from_pmtiles(reader) m = Map(layer) ``` -------------------------------- ### List Directories within a Release Source: https://github.com/developmentseed/lonboard/blob/main/examples/overture-geoparquet.ipynb Uses `list_with_delimiter` to inspect the directory structure within a specific Overture release, showing available themes. ```python store.list_with_delimiter(prefix=latest) ``` -------------------------------- ### Transform Graph Data to Table Structure Source: https://github.com/developmentseed/lonboard/blob/main/examples/migration.ipynb Processes raw graph data into a table format where each row represents an arc between source and target counties. This transformation is ported from a deck.gl JavaScript example. ```python arcs = [] targets = [] sources = [] pairs = {} features = source_data["features"] for i, county in enumerate(features): flows = county["properties"]["flows"] target_centroid = county["properties"]["centroid"] total_value = { "gain": 0, "loss": 0, } for to_id, value in flows.items(): if value > 0: total_value["gain"] += value else: total_value["loss"] += value # If number is too small, ignore it if abs(value) < 50: continue pair_key = "-".join(map(str, sorted([i, int(to_id)]))) source_centroid = features[int(to_id)]["properties"]["centroid"] gain = np.sign(value) # add point at arc source sources.append( { "position": source_centroid, "target": target_centroid, "name": features[int(to_id)]["properties"]["name"], "radius": 3, "gain": -gain, }, ) # eliminate duplicate arcs if pair_key in pairs: continue pairs[pair_key] = True if gain > 0: arcs.append( { "target": target_centroid, "source": source_centroid, "value": value, }, ) else: arcs.append( { "target": source_centroid, "source": target_centroid, "value": value, }, ) # add point at arc target targets.append( { **total_value, "position": [target_centroid[0], target_centroid[1], 10], "net": total_value["gain"] + total_value["loss"], "name": county["properties"]["name"], }, ) # sort targets by radius large -> small targets = sorted(targets, key=lambda d: abs(d["net"]), reverse=True) normalizer = Normalize(0, abs(targets[0]["net"])) ``` -------------------------------- ### Explicit Widget Display in Python with Pyinstrument Source: https://github.com/developmentseed/lonboard/blob/main/DEVELOP.md Use this method when map rendering in Python is slow. It requires explicit opt-in to the display process to allow pyinstrument to hook into it. ```python from IPython.display import display %%pyinstrument display(m) ``` -------------------------------- ### Load Pyinstrument Extension Source: https://github.com/developmentseed/lonboard/blob/main/DEVELOP.md Load the pyinstrument extension in a Jupyter notebook to enable code profiling. This is a magic command. ```python %load_ext pyinstrument ``` -------------------------------- ### Define and manage bounding box for spatial queries Source: https://github.com/developmentseed/lonboard/blob/main/examples/marimo/nyc_taxi_trips.md Initializes a Marimo state variable for a bounding box and provides functions to get and set it. This bounding box is used for spatial intersection queries and can be interactively updated by drawing on the map. ```python get_bbox, set_bbox = mo.state([-74.258843, 40.476578, -73.700233, 40.91763]) ``` -------------------------------- ### Build a Lonboard Application with Panel Source: https://github.com/developmentseed/lonboard/blob/main/docs/ecosystem/panel.md This snippet shows how to integrate Lonboard's Map component within a Panel application. It includes data loading, custom component definition, and layout management for a dynamic geospatial visualization. ```python import colorcet as cc import geopandas as gpd import param from lonboard import Map, PathLayer from lonboard.colormap import apply_continuous_cmap from lonboard._viewport import compute_view from palettable.palette import Palette import panel as pn pn.extension("ipywidgets") url = "https://naciscdn.org/naturalearth/10m/cultural/ne_10m_roads_north_america.zip" @pn.cache def get_data(): return gpd.read_file(filename=url, engine="pyogrio") gdf = get_data() state_options = sorted(state for state in gdf["state"].unique() if state) description = """# Lonboard A Python library for **fast, interactive geospatial data visualization** in Jupyter (and Panel). By utilizing new technologies like `GeoArrow` and `GeoParquet` in conjunction with GPU-based map rendering, Lonboard aims to enable visualizing large geospatial datasets interactively through a simple interface.""" logo = pn.pane.Image( "https://github.com/developmentseed/lonboard/raw/main/assets/dalle-lonboard.jpg" ) def to_rgb(hex: str) -> list: h = hex.strip("#") return list(int(h[i : i + 2], 16) for i in (0, 2, 4)) def to_palette(cmap) -> Palette: """Returns the ColorCet colormap as a palettable Palette""" colors = [to_rgb(item) for item in cmap] return Palette(name="colorcet", map_type="colorcet", colors=colors) class StateViewer(pn.viewable.Viewer): value: Map = param.ClassSelector(class_=Map, doc="The map object", constant=True) state: str = param.Selector(default="California", objects=state_options) cmap: str = param.Selector(default=cc.fire, objects=cc.palette, label="cmap by Colorcet") alpha: float = param.Number(default=0.8, bounds=(0, 1)) data = param.DataFrame() def __init__(self, **params): params["value"] = params.get("value", Map(layers=[], view_state={"longitude": -119.81446785010868, "latitude": 36.08305565437565, "zoom": 5})) super().__init__(**params) self.value.layout.width=self.value.layout.height="100%" self.description = pn.Column(pn.pane.Markdown(description, margin=5), logo) self.settings = pn.Column( pn.widgets.Select.from_param(self.param.state, sizing_mode="stretch_width"), pn.widgets.ColorMap.from_param( self.param.cmap, ncols=3, swatch_width=100, name="cmap by Colorcet", sizing_mode="stretch_width", ), pn.widgets.FloatSlider.from_param( self.param.alpha, sizing_mode="stretch_width" ), margin=5, sizing_mode="fixed", width=300, ) self.view = pn.Column( self._title, pn.pane.IPyWidget(self.value, sizing_mode="stretch_both") ) self._layout = pn.Row( pn.Column(self.settings, sizing_mode="fixed", width=300), self.view, sizing_mode="stretch_both", ) def __panel__(self): return self._layout @param.depends("state", watch=True, on_init=True) def _update_data(self): self.data = gdf[gdf["state"] == self.state] def _get_color(self): palette = to_palette(self.cmap) normalized_scale_rank = (self.data["scalerank"] - 3) / 9 return apply_continuous_cmap(normalized_scale_rank, palette, alpha=self.alpha) @param.depends("data", watch=True) def _update_value(self): layer = PathLayer.from_geopandas(self.data, width_min_pixels=0.8) layer.get_color = self._get_color() self.value.layers = [layer] self._fly_to_center() def _fly_to_center(self): computed_view_state = compute_view(self.value.layers) self.value.fly_to( **computed_view_state, duration=1000, ) @param.depends("cmap", "alpha", watch=True) def _update_layer_get_color(self): self.value.layers[0].get_color = self._get_color() @param.depends("state") def _title(self): return f"# North America Roads: {self.state}" viewer = StateViewer() pn.template.FastListTemplate( logo="https://panel.holoviz.org/_static/logo_horizontal_dark_theme.png", title="Works with Lonboard", sidebar=[viewer.description, viewer.settings], main=[viewer.view], main_layout=None, ).servable() ``` -------------------------------- ### Load Geospatial Data with Arrow Backend using GeoPandas Source: https://github.com/developmentseed/lonboard/blob/main/docs/performance.md Use this when reading geospatial files with GeoPandas to load data directly into Arrow-based columns, avoiding conversion overhead. Specify `engine="pyogrio"` and ensure pyogrio version 0.7 or later is installed. ```python import geopandas as gpd import pandas as pd arrow_to_pandas_kwargs = { 'types_mapper': lambda pa_dtype: pd.ArrowDtype(pa_dtype) } gdf = gpd.read_file( "path/to/file", engine="pyogrio", use_arrow=True, arrow_to_pandas_kwargs=arrow_to_pandas_kwargs ) ``` -------------------------------- ### Update Lonboard Map In Place with Panel Source: https://github.com/developmentseed/lonboard/blob/main/docs/ecosystem/panel.md Update Lonboard map layers dynamically within a Panel application. This example uses a Panel Select widget to change the color of scatterplot points, demonstrating in-place updates without redrawing the entire map. Requires 'panel' and 'ipywidgets_bokeh'. ```python import geopandas as gpd from lonboard import Map, ScatterplotLayer import panel as pn pn.extension("ipywidgets") colors = { "Red": [200, 0, 0], "Green": [0, 200, 0], "Blue": [0, 0, 200], } @pn.cache def get_data(): return gpd.read_file(r"https://naciscdn.org/naturalearth/110m/cultural/ne_110m_populated_places_simple.zip") gdf = get_data() layer = ScatterplotLayer.from_geopandas(gdf, radius_min_pixels=2, get_fill_color="red") cities_map = Map(layer) # Fit to the available space cities_map.layout.height = cities_map.layout.width = "100%" color_input = pn.widgets.Select( name="Color", options=list(colors.keys()), description="The color of the points" ) @pn.depends(value=color_input, watch=True) def set_fill_color(value): cities_map.layers[0].get_fill_color = colors[value] pn.Column( color_input, pn.pane.IPyWidget(cities_map, height=500, width=1000), ).servable() ``` -------------------------------- ### Open GeoTIFF instance Source: https://github.com/developmentseed/lonboard/blob/main/examples/raster-cog-rgb-server.ipynb Open a GeoTIFF file from a specified path within the S3 bucket using the previously created store. ```python # Open our GeoTIFF instance cog_path = "sentinel-s2-l2a-cogs/18/T/WL/2026/1/S2B_18TWL_20260101_0_L2A/TCI.tif" geotiff = await GeoTIFF.open(cog_path, store=store) ``` -------------------------------- ### Initialize Lonboard Map with Layers Source: https://github.com/developmentseed/lonboard/blob/main/examples/overture-geoparquet.ipynb Creates a Lonboard Map object, applying the previously defined polygon layers and setting the basemap style to DarkMatter. ```python m = Map(layers, height=600, basemap_style=CartoBasemap.DarkMatter) ``` -------------------------------- ### Open and Render a GeoTIFF Layer Source: https://github.com/developmentseed/lonboard/blob/main/docs/blog/posts/initial-cog.md Opens a GeoTIFF file and renders it as a raster layer on a map. Ensure the `render_tile` callback is defined to convert tile data to an image format. ```python cog_path = "new-zealand/new-zealand_2024-2025_10m/rgb/2193/CC11.tiff" geotiff = await GeoTIFF.open(cog_path, store=store) # Define our render callback. It must return an instance of `EncodedImage`. def render_tile(tile: Tile) -> EncodedImage: """Convert the array data from the GeoTIFF to an RGB PNG.""" # Reshape from (bands, height, width) to (height, width, bands) image_array = reshape_as_image(tile.array.data) # For some COGs you may need more logic here to convert pixel data to RGB, # but in this case our data is already RGB # Encode as PNG, in this case using PIL img = Image.fromarray(image_array) buf = io.BytesIO() img.save(buf, format="PNG") return EncodedImage(data=buf.getvalue(), media_type="image/png") # Create a RasterLayer and put it on a map layer = RasterLayer.from_geotiff(geotiff, render_tile=render_tile) m = Map(layer) m ``` -------------------------------- ### Create Map Layer and Render Source: https://github.com/developmentseed/lonboard/blob/main/examples/integrations/sidecar.ipynb Create a ScatterplotLayer from the GeoDataFrame and initialize a Lonboard Map. Render the map within the Sidecar context to display it on the right side of the JupyterLab interface. ```python layer = ScatterplotLayer.from_geopandas(gdf) map_ = Map(layers=[layer]) ``` ```python with sc: display(map_) ``` -------------------------------- ### Create and configure TripsLayer Source: https://github.com/developmentseed/lonboard/blob/main/examples/air-traffic-control.ipynb Initializes a Lonboard TripsLayer with the parsed Arrow table, specifying timestamp column, visual properties, and performance settings. ```python layer = TripsLayer( table=table, get_timestamps=table["timestamp"], width_min_pixels=2, get_color=[30, 30, 200, 200], trail_length=200, # Turn off tooltip data selection for better performance pickable=False, ) ``` -------------------------------- ### TripsLayer Initialization Source: https://github.com/developmentseed/lonboard/blob/main/docs/api/layers/trips-layer.md This snippet shows how to initialize the TripsLayer with specific options, including filters. ```APIDOC ## TripsLayer ### Description Initializes a TripsLayer with specified options. ### Method `__init__` ### Parameters #### Options - **filters** (list of str) - Optional - A list of filters to apply to the layer. Example: `["!^_", "!from_duckdb", "!from_geopandas"]`. - **inherited_members** (bool) - Optional - Whether to inherit members from parent classes. Defaults to `true`. ``` -------------------------------- ### Create a BitmapLayer with interleaved rendering Source: https://github.com/developmentseed/lonboard/blob/main/examples/interleaved-labels.ipynb Create a `BitmapLayer` and specify the `before_id` property to control its rendering position within the Maplibre basemap. The layer will render just before the Maplibre layer with the matching ID. Use layer IDs from the basemap style JSON to determine the correct insertion point. ```python layer = BitmapLayer( image="https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/sf-districts.png", bounds=[-122.5190, 37.7045, -122.355, 37.829], before_id="watername_ocean", ) ``` -------------------------------- ### Initialize Brushing Extension Source: https://github.com/developmentseed/lonboard/blob/main/examples/migration.ipynb Initializes the BrushingExtension and sets the brushing radius. This is used for interactive selection of elements on the map. ```python brushing_extension = BrushingExtension() brushing_radius = 200000 ``` -------------------------------- ### Create Map with ScatterplotLayer and DataFilterExtension Source: https://github.com/developmentseed/lonboard/blob/main/examples/data-filter-extension.ipynb Initializes a Sidecar for map display and creates a ScatterplotLayer using the prepared data, styling, and the DataFilterExtension. The extension is crucial for enabling filtering. ```python sidecar = Sidecar(anchor="split-right") layer = ScatterplotLayer.from_geopandas( gdf, extensions=[filter_extension], get_fill_color=fill_color, get_radius=radius, get_filter_value=filter_values, filter_range=initial_filter_range, radius_units="meters", radius_min_pixels=0.1, ) m = Map(layer) with sidecar: display(m) ``` -------------------------------- ### Open GeoTIFF from S3 Source: https://github.com/developmentseed/lonboard/blob/main/examples/raster-cog-nlcd-server.ipynb Opens a Cloud-Optimized GeoTIFF file from an S3 bucket using the Async-GeoTIFF library and the previously configured Obstore store. ```python # Open our GeoTIFF instance cog_path = "cog/Annual_NLCD_LndCov_2024_CU_C1V1.tif" geotiff = await GeoTIFF.open(cog_path, store=store) ``` -------------------------------- ### Import Libraries for Overture Maps and Lonboard Source: https://github.com/developmentseed/lonboard/blob/main/examples/overture-maps.ipynb Import necessary libraries including numpy, overturemaps, matplotlib colormaps, palettable, and Lonboard components for map visualization. ```python import numpy as np import overturemaps from matplotlib.colors import LogNorm from palettable.colorbrewer.sequential import Oranges_9 from lonboard import Map, PolygonLayer from lonboard.colormap import apply_continuous_cmap ``` -------------------------------- ### Create and Render Lonboard Map Source: https://github.com/developmentseed/lonboard/blob/main/examples/raster-cog-nlcd-server.ipynb Instantiates a Lonboard Map with the created raster layer and renders it within the Sidecar container. ```python # Create the map m = Map(layer, height=800) # Render the map in the split screen with sidecar: display(m) ``` -------------------------------- ### Initialize Map with TripsLayer Source: https://github.com/developmentseed/lonboard/blob/main/examples/ais-movingpandas.ipynb Creates a Lonboard Map object and adds the TripsLayer to it, setting a specified height for the map container. ```python m = Map(trips_layer, height=600) m ``` -------------------------------- ### Set up Sidecar for Map Display Source: https://github.com/developmentseed/lonboard/blob/main/examples/raster-cog-nlcd-server.ipynb Initializes a Sidecar instance to display the Lonboard map, typically in a split view within JupyterLab. ```python # In JupyterLab, split the screen to render the map on the right sidecar = Sidecar(anchor="split-right") ``` -------------------------------- ### List Building Data Directories Source: https://github.com/developmentseed/lonboard/blob/main/examples/overture-geoparquet.ipynb Further inspects the directory structure to find specific data types, such as building data, by providing a more specific prefix. ```python store.list_with_delimiter(prefix=f"{latest}/theme=buildings") ``` -------------------------------- ### Import Necessary Libraries Source: https://github.com/developmentseed/lonboard/blob/main/examples/raster-cog-nlcd-server.ipynb Imports required modules for handling GeoTIFFs, S3 storage, image manipulation, and Lonboard map visualization. ```python import io import numpy as np from async_geotiff import GeoTIFF, Tile from obstore.store import S3Store from PIL import Image from sidecar import Sidecar from lonboard import Map, RasterLayer from lonboard.raster import EncodedImage ``` -------------------------------- ### lonboard.viz Source: https://github.com/developmentseed/lonboard/blob/main/docs/api/viz.md The main visualization module for lonboard. ```APIDOC ## lonboard.viz This module provides functionalities for creating and managing visualizations within the lonboard framework. It serves as the primary interface for users to access various plotting and rendering capabilities. ``` -------------------------------- ### Display Map with Polygon Layer Source: https://github.com/developmentseed/lonboard/blob/main/examples/global-boundaries.ipynb Instantiate a Map object with the created PolygonLayer and display it. ```python m = Map(layer) m ``` -------------------------------- ### Initialize Lonboard Map with View State Source: https://github.com/developmentseed/lonboard/blob/main/examples/overture-maps.ipynb Initialize a Lonboard Map with the created PolygonLayer and a predefined view state for NYC. This sets the initial camera position, zoom, pitch, and bearing for the map. ```python view_state = { "longitude": -73.98416810282863, "latitude": 40.72651721370669, "zoom": 12.726630492730596, "pitch": 59.80465353190481, "bearing": 13.243243243243244, } m = Map(layer, view_state=view_state) m ``` -------------------------------- ### Fetch and Prepare Data Source: https://github.com/developmentseed/lonboard/blob/main/examples/data-filter-extension.ipynb Downloads parquet data from a URL, extracts relevant columns, calculates tile centroids, and creates a GeoDataFrame. Caches the data locally to speed up subsequent runs. ```python url = "https://ookla-open-data.s3.us-west-2.amazonaws.com/parquet/performance/type=mobile/year=2019/quarter=1/2019-01-01_performance_mobile_tiles.parquet" local_path = Path("data-filter-extension.parquet") if local_path.exists(): gdf = gpd.read_parquet(local_path) else: columns = ["avg_d_kbps", "avg_u_kbps", "avg_lat_ms", "devices", "tile"] df = pd.read_parquet(url, columns=columns) tile_geometries = shapely.from_wkt(df["tile"]) tile_centroids = shapely.centroid(tile_geometries) non_geom_columns = [col for col in columns if col != "tile"] gdf = gpd.GeoDataFrame( df[non_geom_columns], geometry=tile_centroids, crs="EPSG:4326", ) gdf.to_parquet(local_path) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/developmentseed/lonboard/blob/main/examples/air-traffic-control.ipynb Imports required libraries for data handling, network requests, and Lonboard visualization. ```python from datetime import timedelta from io import BytesIO import requests from arro3.io import read_parquet from lonboard import Map, TripsLayer ``` -------------------------------- ### Display DataFrame Head and Columns Source: https://github.com/developmentseed/lonboard/blob/main/examples/map_challenge/1-points.ipynb Configures pandas to display all columns and then shows the first five rows of the DataFrame. This is useful for a quick overview of the data structure and content. ```python pd.options.display.max_columns = None df.head() ``` ```python df.columns ``` -------------------------------- ### Create Custom Environment Variables Source: https://github.com/developmentseed/lonboard/blob/main/DEVELOP.md Create a .env file to define custom environment variables for the JavaScript component. This file is ignored by git. ```bash VARIABLE="setting" ``` -------------------------------- ### Create Lonboard PolygonLayer for Buildings Source: https://github.com/developmentseed/lonboard/blob/main/examples/overture-maps.ipynb Create a PolygonLayer in Lonboard, specifying the table, extrusion, height, and fill color for each building. Only relevant attribute columns are selected from the table. ```python layer = PolygonLayer( # Select only a few attribute columns from the table table=table.select(["id", "height", "geometry", "names"]), extruded=True, get_elevation=heights, get_fill_color=colors, ) ``` -------------------------------- ### Initialize DataFusion SessionContext and register extensions Source: https://github.com/developmentseed/lonboard/blob/main/examples/marimo/nyc_taxi_trips.md Sets up a DataFusion session and registers the GeoDataFusion spatial extension. It also registers a Parquet file as a table named 'trips' for querying. ```python ctx = SessionContext() register_all(ctx) ctx.register_parquet("trips", output_path) ``` -------------------------------- ### Create Marimo UI Controls Source: https://github.com/developmentseed/lonboard/blob/main/examples/marimo/nyc_taxi_trips.md Create horizontal stacks of Marimo UI elements like toggles and sliders. Use justify to align elements within the stack. ```python toggles = mo.hstack([arc_layer_enabled, pickup_layer_enabled, brushing_toggle]) sliders = mo.hstack([arc_opacity, brushing_radius], justify="start") mo.vstack([m, toggles, sliders]) ``` -------------------------------- ### Create ScatterplotLayer with DataFilterExtension Source: https://github.com/developmentseed/lonboard/blob/main/examples/data-filter-extension-categorical.ipynb Initializes a ScatterplotLayer from GeoDataFrame, applying a continuous colormap for price and configuring the DataFilterExtension for categorical filtering. It sets up filtering for two categories (bedrooms and bathrooms) and initializes filter categories as empty lists. ```python min_bound = home_sales_df["price"].quantile(0.05) max_bound = home_sales_df["price"].quantile(0.95) price = home_sales_df["price"] normalized_price = (price - min_bound) / (max_bound - min_bound) home_sale_layer = ScatterplotLayer.from_geopandas( home_sales_df, get_fill_color=lonboard.colormap.apply_continuous_cmap(normalized_price, RdYlGn_11), radius_min_pixels=5, extensions=[ DataFilterExtension(filter_size=None, category_size=2), ], get_filter_category=home_sales_df[["bedrooms", "bathrooms"]].values, filter_categories=[[], []], ) ``` -------------------------------- ### Create Interactive Widgets for Categorical Filtering Source: https://github.com/developmentseed/lonboard/blob/main/examples/data-filter-extension-categorical.ipynb Set up `SelectMultiple` widgets for 'bedrooms' and 'bathrooms' to filter data. Includes functions to observe changes and update the layer's `filter_categories` property. If a select widget has no selection, all values are used. ```python unique_bedrooms_values = list(home_sales_df["bedrooms"].sort_values().unique()) unique_bathrooms_values = list(home_sales_df["bathrooms"].sort_values().unique()) bedrooms_select = SelectMultiple(description="Bedrooms", options=unique_bedrooms_values) bathrooms_select = SelectMultiple( description="Bathrooms", options=unique_bathrooms_values, ) def on_select_change(_: traitlets.utils.bunch.Bunch = None) -> None: """Set the layer's filter_categories property based on widget selections.""" bedrooms = bedrooms_select.value bathrooms = bathrooms_select.value if len(bedrooms) == 0: bedrooms = unique_bedrooms_values if len(bathrooms) == 0: bathrooms = unique_bathrooms_values home_sale_layer.filter_categories = [bedrooms, bathrooms] bedrooms_select.observe(on_select_change, "value") bathrooms_select.observe(on_select_change, "value") clear_bedrooms_button = Button(description="Clear Bedrooms") def clear_bedrooms(_: Button) -> None: bedrooms_select.value = [] clear_bedrooms_button.on_click(clear_bedrooms) clear_bathrooms_button = Button(description="Clear Bathrooms") def clear_bathrooms(_: Button) -> None: bathrooms_select.value = [] clear_bathrooms_button.on_click(clear_bathrooms) home_sale_map = Map( layers=[home_sale_layer], basemap=lonboard.basemap.MaplibreBasemap(), ) on_select_change() # fire the function once to initially set the layer's filter_categories, and display all points display(home_sale_map) display( HBox( [ VBox([bedrooms_select, clear_bedrooms_button]), VBox([bathrooms_select, clear_bathrooms_button]), ], ), ) ``` -------------------------------- ### Initialize MaplibreBasemap in interleaved mode Source: https://github.com/developmentseed/lonboard/blob/main/examples/interleaved-labels.ipynb Instantiate `MaplibreBasemap` with `mode='interleaved'` to enable rendering Lonboard layers within the Maplibre stack. Choose a `CartoStyle` for the basemap. ```python basemap = MaplibreBasemap(mode="interleaved", style=CartoStyle.DarkMatter) ``` -------------------------------- ### Initialize DataFilterExtension Source: https://github.com/developmentseed/lonboard/blob/main/examples/data-filter-extension.ipynb Creates an instance of DataFilterExtension with a specified filter size. This extension enables multi-attribute filtering on layers. ```python filter_extension = DataFilterExtension(filter_size=3) ``` -------------------------------- ### Create Lonboard Map Source: https://github.com/developmentseed/lonboard/blob/main/examples/raster-cog-rgb-server.ipynb Create a Lonboard Map instance, passing the RasterLayer to be displayed and specifying the desired height. ```python # Create the map m = Map(layer, height=800) ```