From 4b1f4deef7af8a675424283c02ec272bb48b4005 Mon Sep 17 00:00:00 2001 From: Qiusheng Wu Date: Sat, 26 Oct 2024 17:58:21 -0400 Subject: [PATCH] Update Maplibre chapter (#130) * Update Maplibre chapter * Update intro * Skip maplibre execute * Update maplibre lecture * Update leafmap version * Add description --- .github/workflows/build.yml | 2 + .github/workflows/deploy.yml | 2 + .gitignore | 3 +- _config.yml | 2 - book/geospatial/maplibre.ipynb | 3883 ++++++++++++++++++++++---------- book/geospatial/maplibre.md | 1889 ++++++++++++---- 6 files changed, 4169 insertions(+), 1612 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6fe4d54..ed362e5 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -30,6 +30,7 @@ jobs: - name: Install dependencies run: | uv sync --python ${{ matrix.python-version }} + uv pip install -U leafmap uv pip install py3dep - name: Install optional dependencies @@ -49,6 +50,7 @@ jobs: env: AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + MAPTILER_KEY: ${{ secrets.MAPTILER_KEY }} - name: Deploy to Netlify uses: nwtgck/actions-netlify@v3.0 with: diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index bc264d0..4fa49c0 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -30,6 +30,7 @@ jobs: - name: Install dependencies run: | uv sync --python ${{ matrix.python-version }} + uv pip install -U leafmap uv pip install py3dep - name: Install optional dependencies @@ -49,6 +50,7 @@ jobs: env: AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + MAPTILER_KEY: ${{ secrets.MAPTILER_KEY }} # Deploy the book's HTML to gh-pages branch - name: GitHub Pages action uses: peaceiris/actions-gh-pages@v4 diff --git a/.gitignore b/.gitignore index a2efcd7..0d031a2 100644 --- a/.gitignore +++ b/.gitignore @@ -44,4 +44,5 @@ pour_point* streams* watershed* histogram* -book/geospatial/cache/* \ No newline at end of file +book/geospatial/cache/* +book/geospatial/*.html \ No newline at end of file diff --git a/_config.yml b/_config.yml index 401399f..dd1c704 100644 --- a/_config.yml +++ b/_config.yml @@ -20,8 +20,6 @@ execute: execute_notebooks: "auto" # Whether to execute notebooks at build time. Must be one of ("auto", "force", "cache", "off") cache: "" # A path to the jupyter cache that will be used to store execution artifacts. Defaults to `_build/.jupyter_cache/` exclude_patterns: [ - "book/geospatial/vector_viz.ipynb", - "book/geospatial/raster_viz.ipynb", "book/geospatial/maplibre.ipynb", "book/geospatial/geemap.ipynb", "book/geospatial/samgeo.ipynb", diff --git a/book/geospatial/maplibre.ipynb b/book/geospatial/maplibre.ipynb index e2262e0..4f366db 100644 --- a/book/geospatial/maplibre.ipynb +++ b/book/geospatial/maplibre.ipynb @@ -11,11 +11,18 @@ "\n", "## Overview\n", "\n", - "The notebook demonstrates how to create 3D maps using the [MapLibre](https://github.com/eodaGmbH/py-maplibregl) Python package. The examples shown in this notebook are based on the [MapLibre documentation](https://eodagmbh.github.io/py-maplibregl/examples/vancouver_blocks/). \n", + "This lecture introduces the [MapLibre](https://github.com/eodaGmbH/py-maplibregl) Python package, a flexible open-source mapping Python package that allows users to create interactive and customizable 3D and 2D maps in Python. By leveraging the MapLibre library, GIS developers can visualize geospatial data with a variety of customization options and mapping styles. The notebook demonstrates essential concepts like creating interactive maps, customizing basemaps, adding various data layers, and implementing map controls for enhanced functionality. Additionally, advanced features, such as 3D building visualization and layer control, provide students with practical tools for real-world geospatial data analysis and visualization.\n", "\n", - "## Learning Objectives\n", + "## Learning Outcomes\n", "\n", - "TBA. \n", + "By the end of this lecture, students will be able to:\n", + "\n", + "1. Set up and install MapLibre for geospatial visualization in Python.\n", + "2. Create basic interactive maps and apply different basemap styles.\n", + "3. Customize map features, including markers, lines, polygons, and map controls.\n", + "4. Utilize advanced features such as 3D buildings and choropleth maps.\n", + "5. Integrate and manage multiple data layers, including GeoJSON, raster, and vector layers.\n", + "6. Export map visualizations as standalone HTML files for sharing and deployment.\n", "\n", "## Useful Resources\n", "\n", @@ -23,9 +30,9 @@ "- Videos: https://bit.ly/maplibre\n", "- Demos: https://maps.gishub.org\n", "\n", - "## Installation\n", + "## Installation and Setup\n", "\n", - "Uncomment the following line to install the required Python packages." + "To install the required packages, uncomment and run the line below." ] }, { @@ -43,7 +50,7 @@ "id": "2", "metadata": {}, "source": [ - "Import the maplibre mapping backend." + "Once installed, import the `maplibregl` backend from the `leafmap` package:" ] }, { @@ -61,9 +68,11 @@ "id": "4", "metadata": {}, "source": [ - "## Set up API Key\n", + "## Creating Interactive Maps\n", + "\n", + "### Basic Map Setup\n", "\n", - "To run this notebook, you need to set up a MapTiler API key. You can get a free API key by signing up at [https://cloud.maptiler.com/](https://cloud.maptiler.com/)." + "Let’s start by creating a simple interactive map with default settings. This basic setup provides a blank canvas on which you can add data layers, controls, and other customizations." ] }, { @@ -73,8 +82,8 @@ "metadata": {}, "outputs": [], "source": [ - "# import os\n", - "# os.environ[\"MAPTILER_KEY\"] = \"YOUR_API_KEY\"" + "m = leafmap.Map()\n", + "m" ] }, { @@ -82,11 +91,9 @@ "id": "6", "metadata": {}, "source": [ - "## Create interactive maps\n", + "### Customizing the Map's Center and Zoom Level\n", "\n", - "### Create a simple map\n", - "\n", - "Let's create a simple interactive map using Leafmap." + "You can specify the map’s center (latitude and longitude), zoom level, pitch, and bearing for a more focused view. These parameters help direct the user's attention to specific areas." ] }, { @@ -96,7 +103,7 @@ "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map()\n", + "m = leafmap.Map(center=[-100, 40], zoom=3, pitch=0, bearing=0)\n", "m" ] }, @@ -105,7 +112,9 @@ "id": "8", "metadata": {}, "source": [ - "You can customize the map by specifying map center [lon, lat], zoom level, pitch, and bearing." + "### Choosing a Basemap Style\n", + "\n", + "MapLibre supports several pre-defined basemap styles such as `dark-matter`, `positron`, `voyager`, `liberty`, `demotiles`. You can also use custom basemap URLs for unique styling." ] }, { @@ -115,41 +124,35 @@ "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-100, 40], zoom=3, pitch=0, bearing=0)\n", + "m = leafmap.Map(style=\"positron\")\n", "m" ] }, - { - "cell_type": "markdown", - "id": "10", - "metadata": {}, - "source": [ - "To customize the basemap, you can specify the `style` parameter. It can be an URL or a string, such as `dark-matter`, `positron`, `voyager`, `liberty`, `demotiles`." - ] - }, { "cell_type": "code", "execution_count": null, - "id": "11", + "id": "10", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(style=\"positron\")\n", + "m = leafmap.Map(style=\"liberty\")\n", "m" ] }, { "cell_type": "markdown", - "id": "12", + "id": "11", "metadata": {}, "source": [ - "To create a map with a background color, use `style=\"background-\"`, such as `background-lightgray` and `background-green`." + "### Adding Background Colors\n", + "\n", + "Background color styles, such as `background-lightgray` and `background-green`, are helpful for simple or thematic maps where color-coding is needed." ] }, { "cell_type": "code", "execution_count": null, - "id": "13", + "id": "12", "metadata": {}, "outputs": [], "source": [ @@ -159,7 +162,7 @@ }, { "cell_type": "markdown", - "id": "14", + "id": "13", "metadata": {}, "source": [ "Alternatively, you can provide a URL to a vector style." @@ -168,7 +171,7 @@ { "cell_type": "code", "execution_count": null, - "id": "15", + "id": "14", "metadata": {}, "outputs": [], "source": [ @@ -179,18 +182,30 @@ }, { "cell_type": "markdown", - "id": "16", + "id": "15", "metadata": {}, "source": [ - "### Add map controls\n", + "## Adding Map Controls\n", + "\n", + "Map controls enhance the usability of the map by allowing users to interact in various ways, adding elements like scale bars, zoom tools, and drawing options.\n", + "\n", + "### Available Controls\n", + "\n", + "- **Scale**: Adds a scale bar to indicate the map’s scale.\n", + "- **Fullscreen**: Expands the map to a full-screen view for better focus.\n", + "- **Geolocate**: Centers the map based on the user’s current location, if available.\n", + "- **Navigation**: Provides zoom controls and a compass for reorientation.\n", + "- **Draw**: Allows users to draw and edit shapes on the map.\n", "\n", - "The control to add to the map. Can be one of the following: `scale`, `fullscreen`, `geolocate`, `navigation`." + "### Adding Geolocate Control\n", + "\n", + "The Geolocate control centers the map based on the user’s current location, a helpful feature for location-based applications." ] }, { "cell_type": "code", "execution_count": null, - "id": "17", + "id": "16", "metadata": {}, "outputs": [], "source": [ @@ -201,73 +216,86 @@ }, { "cell_type": "markdown", - "id": "18", + "id": "17", "metadata": {}, "source": [ - "### Add basemaps\n", + "### Adding Fullscreen Control\n", "\n", - "You can add basemaps to the map using the `add_basemap` method." + "Fullscreen control enables users to expand the map to full screen, enhancing focus and visual clarity. This is especially useful when viewing complex or large datasets." ] }, { "cell_type": "code", "execution_count": null, - "id": "19", + "id": "18", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map()\n", - "m.add_basemap(\"OpenTopoMap\")\n", + "m = leafmap.Map(center=[11.255, 43.77], zoom=13, style=\"streets\", controls={})\n", + "m.add_control(\"fullscreen\", position=\"top-right\")\n", "m" ] }, { - "cell_type": "code", - "execution_count": null, - "id": "20", + "cell_type": "markdown", + "id": "19", "metadata": {}, - "outputs": [], "source": [ - "m.add_basemap(\"Esri.WorldImagery\")" + "### Adding Navigation Control\n", + "\n", + "The Navigation control provides buttons for zooming and reorienting the map, improving the user's ability to navigate efficiently." ] }, { "cell_type": "code", "execution_count": null, - "id": "21", + "id": "20", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map()\n", + "m = leafmap.Map(center=[11.255, 43.77], zoom=13, style=\"streets\", controls={})\n", + "m.add_control(\"navigation\", position=\"top-left\")\n", "m" ] }, { "cell_type": "markdown", - "id": "22", + "id": "21", "metadata": {}, "source": [ - "To add basemaps interactively, use the `add_basemap` method without specifying the `basemap` parameter." + "### Adding Draw Control\n", + "\n", + "The Draw control enables users to interact with the map by adding shapes such as points, lines, and polygons. This control is essential for tasks requiring spatial data input directly on the map." ] }, { "cell_type": "code", "execution_count": null, - "id": "23", + "id": "22", "metadata": {}, "outputs": [], "source": [ - "m.add_basemap()" + "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", + "m.add_draw_control(position=\"top-left\")\n", + "m" ] }, { "cell_type": "markdown", + "id": "23", + "metadata": {}, + "source": [ + "You can configure the Draw control to activate specific tools, like polygon, line, or point drawing, while also enabling or disabling a \"trash\" button to remove unwanted shapes." + ] + }, + { + "cell_type": "code", + "execution_count": null, "id": "24", "metadata": {}, + "outputs": [], "source": [ - "### Add XYZ tile layer\n", - "\n", - "You can add XYZ tile layers to the map using the `add_tile_layer` method." + "from maplibre.plugins import MapboxDrawControls, MapboxDrawOptions" ] }, { @@ -277,9 +305,12 @@ "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map()\n", - "url = \"https://basemap.nationalmap.gov/arcgis/rest/services/USGSTopo/MapServer/tile/{z}/{y}/{x}\"\n", - "m.add_tile_layer(url, name=\"USGS TOpo\", attribution=\"USGS\", opacity=1.0, visible=True)\n", + "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", + "draw_options = MapboxDrawOptions(\n", + " display_controls_default=False,\n", + " controls=MapboxDrawControls(polygon=True, line_string=True, point=True, trash=True),\n", + ")\n", + "m.add_draw_control(draw_options)\n", "m" ] }, @@ -288,9 +319,7 @@ "id": "26", "metadata": {}, "source": [ - "### Add WMS layer\n", - "\n", - "You can add WMS layers to the map using the `add_wms_layer` method." + "Additionally, you can load a GeoJSON FeatureCollection into the Draw control, which will allow users to view, edit, or interact with pre-defined geographical features, such as boundaries or points of interest." ] }, { @@ -300,38 +329,71 @@ "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-74.5447, 40.6892], zoom=8, style=\"streets\")\n", - "url = \"https://img.nj.gov/imagerywms/Natural2015\"\n", - "layers = \"Natural2015\"\n", - "m.add_wms_layer(url, layers=layers, before_id=\"aeroway_fill\")\n", + "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", + "geojson = {\n", + " \"type\": \"FeatureCollection\",\n", + " \"features\": [\n", + " {\n", + " \"id\": \"abc\",\n", + " \"type\": \"Feature\",\n", + " \"properties\": {},\n", + " \"geometry\": {\n", + " \"coordinates\": [\n", + " [\n", + " [-119.08, 45.95],\n", + " [-119.79, 42.08],\n", + " [-107.28, 41.43],\n", + " [-108.15, 46.44],\n", + " [-119.08, 45.95],\n", + " ]\n", + " ],\n", + " \"type\": \"Polygon\",\n", + " },\n", + " },\n", + " {\n", + " \"id\": \"xyz\",\n", + " \"type\": \"Feature\",\n", + " \"properties\": {},\n", + " \"geometry\": {\n", + " \"coordinates\": [\n", + " [\n", + " [-103.87, 38.08],\n", + " [-108.54, 36.44],\n", + " [-106.25, 33.00],\n", + " [-99.91, 31.79],\n", + " [-96.82, 35.48],\n", + " [-98.80, 37.77],\n", + " [-103.87, 38.08],\n", + " ]\n", + " ],\n", + " \"type\": \"Polygon\",\n", + " },\n", + " },\n", + " ],\n", + "}\n", + "m.add_draw_control(position=\"top-left\", geojson=geojson)\n", "m" ] }, { - "cell_type": "code", - "execution_count": null, + "cell_type": "markdown", "id": "28", "metadata": {}, - "outputs": [], "source": [ - "m = leafmap.Map(center=[-100.307965, 46.98692], zoom=13, pitch=45, style=\"3d-hybrid\")\n", - "url = \"https://fwspublicservices.wim.usgs.gov/wetlandsmapservice/services/Wetlands/MapServer/WMSServer\"\n", - "m.add_wms_layer(url, layers=\"1\", name=\"NWI\", opacity=0.6)\n", - "m.add_layer_control(bg_layers=True)\n", - "m.add_legend(builtin_legend=\"NWI\", title=\"Wetland Type\")\n", - "m" + "Two key methods for accessing drawn features:\n", + "\n", + "- **Selected Features**: Accesses only the currently selected features.\n", + "- **All Features**: Accesses all features added, regardless of selection, giving you full control over the spatial data on the map." ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "id": "29", "metadata": {}, + "outputs": [], "source": [ - "### MapTiler styles\n", - "\n", - "You can use any named style from MapTiler by setting the style parameter to the name of the style.\n", - "\n", - "![](https://i.imgur.com/dp2HxR2.png)" + "m.draw_features_selected" ] }, { @@ -341,19 +403,21 @@ "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(style=\"streets\")\n", - "m" + "m.draw_feature_collection_all" ] }, { - "cell_type": "code", - "execution_count": null, + "cell_type": "markdown", "id": "31", "metadata": {}, - "outputs": [], "source": [ - "m = leafmap.Map(style=\"satellite\")\n", - "m" + "## Add Layers\n", + "\n", + "Adding layers to a map enhances the data it presents, allowing different types of basemaps, tile layers, and thematic overlays to be combined for in-depth analysis.\n", + "\n", + "### Adding Basemaps\n", + "\n", + "Basemaps provide a geographical context for the map. Using the `add_basemap` method, you can select from various basemaps, including `OpenTopoMap` and `Esri.WorldImagery`. Adding a layer control allows users to switch between multiple basemaps interactively." ] }, { @@ -363,7 +427,9 @@ "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(style=\"hybrid\")\n", + "m = leafmap.Map()\n", + "m.add_basemap(\"OpenTopoMap\")\n", + "m.add_layer_control()\n", "m" ] }, @@ -374,32 +440,26 @@ "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(style=\"topo\")\n", - "m" + "m.add_basemap(\"Esri.WorldImagery\")" ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "id": "34", "metadata": {}, + "outputs": [], "source": [ - "## 3D mapping\n", - "\n", - "### 3D terrain\n", - "\n", - "MapTiler provides a variety of basemaps and styles that can be used to create 3D maps. You can use any styles from the MapTiler basemap gallery and prefix the style name with `3d-`. For example, `3d-hybrid`, `3d-satellite`, or `3d-topo`. To use the hillshade only, you can use the `3d-hillshade` style." + "m = leafmap.Map()\n", + "m" ] }, { - "cell_type": "code", - "execution_count": null, + "cell_type": "markdown", "id": "35", "metadata": {}, - "outputs": [], "source": [ - "m = leafmap.Map(style=\"3d-hybrid\")\n", - "m.add_layer_control(bg_layers=True)\n", - "m" + "You can also add basemaps interactively, which provides flexibility for selecting the best background for your map content." ] }, { @@ -409,21 +469,17 @@ "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(style=\"3d-satellite\")\n", - "m.add_layer_control(bg_layers=True)\n", - "m" + "m.add_basemap()" ] }, { - "cell_type": "code", - "execution_count": null, + "cell_type": "markdown", "id": "37", "metadata": {}, - "outputs": [], "source": [ - "m = leafmap.Map(style=\"3d-topo\", exaggeration=1.5, hillshade=False)\n", - "m.add_layer_control(bg_layers=True)\n", - "m" + "### Adding XYZ Tile Layer\n", + "\n", + "XYZ tile layers allow integration of specific tile services like topographic, satellite, or other thematic imagery from XYZ tile servers. By specifying the URL and parameters such as `opacity` and `visibility`, XYZ layers can be customized and styled to fit the needs of your map." ] }, { @@ -433,89 +489,33 @@ "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(style=\"3d-ocean\", exaggeration=1.5, hillshade=True)\n", - "m.add_layer_control(bg_layers=True)\n", - "m" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "39", - "metadata": {}, - "outputs": [], - "source": [ - "m = leafmap.Map(\n", - " center=[-122.19861, 46.21168], zoom=13, pitch=60, bearing=150, style=\"3d-terrain\"\n", - ")\n", - "m.add_layer_control(bg_layers=True)\n", + "m = leafmap.Map()\n", + "url = \"https://basemap.nationalmap.gov/arcgis/rest/services/USGSTopo/MapServer/tile/{z}/{y}/{x}\"\n", + "m.add_tile_layer(url, name=\"USGS TOpo\", attribution=\"USGS\", opacity=1.0, visible=True)\n", "m" ] }, { "cell_type": "markdown", - "id": "40", + "id": "39", "metadata": {}, "source": [ - "### 3D buildings\n", + "### Adding WMS Layer\n", "\n", - "You can add 3D buildings to the map using the `add_3d_buildings` method." + "Web Map Service (WMS) layers provide access to external datasets served by web servers, such as thematic maps or detailed satellite imagery. Adding a WMS layer involves specifying the WMS URL and layer names, which allows for overlaying various data types such as natural imagery or land cover classifications." ] }, { "cell_type": "code", "execution_count": null, - "id": "41", + "id": "40", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(\n", - " center=[-74.01201, 40.70473], zoom=16, pitch=60, bearing=35, style=\"basic-v2\"\n", - ")\n", - "MAPTILER_KEY = leafmap.get_api_key(\"MAPTILER_KEY\")\n", - "m.add_basemap(\"Esri.WorldImagery\", visible=False)\n", - "source = {\n", - " \"url\": f\"https://api.maptiler.com/tiles/v3/tiles.json?key={MAPTILER_KEY}\",\n", - " \"type\": \"vector\",\n", - "}\n", - "\n", - "layer = {\n", - " \"id\": \"3d-buildings\",\n", - " \"source\": \"openmaptiles\",\n", - " \"source-layer\": \"building\",\n", - " \"type\": \"fill-extrusion\",\n", - " \"min-zoom\": 15,\n", - " \"paint\": {\n", - " \"fill-extrusion-color\": [\n", - " \"interpolate\",\n", - " [\"linear\"],\n", - " [\"get\", \"render_height\"],\n", - " 0,\n", - " \"lightgray\",\n", - " 200,\n", - " \"royalblue\",\n", - " 400,\n", - " \"lightblue\",\n", - " ],\n", - " \"fill-extrusion-height\": [\n", - " \"interpolate\",\n", - " [\"linear\"],\n", - " [\"zoom\"],\n", - " 15,\n", - " 0,\n", - " 16,\n", - " [\"get\", \"render_height\"],\n", - " ],\n", - " \"fill-extrusion-base\": [\n", - " \"case\",\n", - " [\">=\", [\"get\", \"zoom\"], 16],\n", - " [\"get\", \"render_min_height\"],\n", - " 0,\n", - " ],\n", - " },\n", - "}\n", - "m.add_source(\"openmaptiles\", source)\n", - "m.add_layer(layer)\n", + "m = leafmap.Map(center=[-74.5447, 40.6892], zoom=8, style=\"liberty\")\n", + "url = \"https://img.nj.gov/imagerywms/Natural2015\"\n", + "layers = \"Natural2015\"\n", + "m.add_wms_layer(url, layers=layers, before_id=\"aeroway_fill\")\n", "m.add_layer_control()\n", "m" ] @@ -523,49 +523,81 @@ { "cell_type": "code", "execution_count": null, - "id": "42", + "id": "41", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(\n", - " center=[-74.01201, 40.70473], zoom=16, pitch=60, bearing=35, style=\"basic-v2\"\n", - ")\n", - "m.add_basemap(\"Esri.WorldImagery\", visible=False)\n", - "m.add_3d_buildings(min_zoom=15)\n", + "m = leafmap.Map(center=[-100.307965, 46.98692], zoom=13, pitch=45, style=\"liberty\")\n", + "m.add_basemap(\"Esri.WorldImagery\")\n", + "url = \"https://fwspublicservices.wim.usgs.gov/wetlandsmapservice/services/Wetlands/MapServer/WMSServer\"\n", + "m.add_wms_layer(url, layers=\"1\", name=\"NWI\", opacity=0.6)\n", "m.add_layer_control()\n", + "m.add_legend(builtin_legend=\"NWI\", title=\"Wetland Type\")\n", "m" ] }, { "cell_type": "markdown", - "id": "43", + "id": "42", "metadata": {}, "source": [ - "### 3D indoor mapping\n", + "### Adding Raster Tiles\n", + "\n", + "Raster tiles provide a set of customized styles for map layers, such as watercolor or artistic styles, which can add unique visual elements. Configuring raster tile styles involves setting tile URLs, tile size, and attribution information. This setup provides access to a wide array of predefined designs, offering creative flexibility in how data is presented.\n", "\n", - "Let's visualize indoor mapping data using the `add_geojson` method." + "With raster tiles, you can control zoom limits and apply unique visual IDs to distinguish between multiple raster sources on the map." ] }, { "cell_type": "code", "execution_count": null, - "id": "44", + "id": "43", "metadata": {}, "outputs": [], "source": [ - "data = \"https://maplibre.org/maplibre-gl-js/docs/assets/indoor-3d-map.geojson\"\n", - "gdf = leafmap.geojson_to_gdf(data)\n", - "gdf.explore()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "45", + "style = {\n", + " \"version\": 8,\n", + " \"sources\": {\n", + " \"raster-tiles\": {\n", + " \"type\": \"raster\",\n", + " \"tiles\": [\n", + " \"https://tiles.stadiamaps.com/tiles/stamen_watercolor/{z}/{x}/{y}.jpg\"\n", + " ],\n", + " \"tileSize\": 256,\n", + " \"attribution\": \"Map tiles by Stamen Design; Hosting by Stadia Maps. Data © OpenStreetMap contributors\",\n", + " }\n", + " },\n", + " \"layers\": [\n", + " {\n", + " \"id\": \"simple-tiles\",\n", + " \"type\": \"raster\",\n", + " \"source\": \"raster-tiles\",\n", + " \"minzoom\": 0,\n", + " \"maxzoom\": 22,\n", + " }\n", + " ],\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "44", "metadata": {}, "outputs": [], "source": [ - "gdf.head()" + "m = leafmap.Map(center=[-74.5, 40], zoom=2, style=style)\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "45", + "metadata": {}, + "source": [ + "## MapTiler\n", + "\n", + "To use MapTiler with this notebook, you need to set up a MapTiler API key. You can obtain a free API key by signing up at [https://cloud.maptiler.com/](https://cloud.maptiler.com/)." ] }, { @@ -575,23 +607,8 @@ "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(\n", - " center=(-87.61694, 41.86625), zoom=17, pitch=40, bearing=20, style=\"positron\"\n", - ")\n", - "m.add_basemap(\"OpenStreetMap.Mapnik\")\n", - "m.add_geojson(\n", - " data,\n", - " layer_type=\"fill-extrusion\",\n", - " name=\"floorplan\",\n", - " paint={\n", - " \"fill-extrusion-color\": [\"get\", \"color\"],\n", - " \"fill-extrusion-height\": [\"get\", \"height\"],\n", - " \"fill-extrusion-base\": [\"get\", \"base_height\"],\n", - " \"fill-extrusion-opacity\": 0.5,\n", - " },\n", - ")\n", - "m.add_layer_control()\n", - "m" + "# import os\n", + "# os.environ[\"MAPTILER_KEY\"] = \"YOUR_API_KEY\"" ] }, { @@ -599,7 +616,16 @@ "id": "47", "metadata": {}, "source": [ - "### 3D choropleth map" + "Set the API key as an environment variable to access MapTiler's resources. Once set up, you can specify any named style from MapTiler by using the style parameter in the map setup.\n", + "\n", + "![](https://i.imgur.com/dp2HxR2.png)\n", + "\n", + "The following are examples of different styles available through MapTiler:\n", + "\n", + "- **Streets style**: This style displays detailed street information and is suited for urban data visualization.\n", + "- **Satellite style**: Provides high-resolution satellite imagery for various locations.\n", + "- **Hybrid style**: Combines satellite imagery with labels for a clear geographic context.\n", + "- **Topo style**: A topographic map showing terrain details, ideal for outdoor-related applications." ] }, { @@ -609,45 +635,7 @@ "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[19.43, 49.49], zoom=3, pitch=60, style=\"basic\")\n", - "source = {\n", - " \"type\": \"geojson\",\n", - " \"data\": \"https://docs.maptiler.com/sdk-js/assets/Mean_age_of_women_at_first_marriage_in_2019.geojson\",\n", - "}\n", - "m.add_source(\"countries\", source)\n", - "layer = {\n", - " \"id\": \"eu-countries\",\n", - " \"source\": \"countries\",\n", - " \"type\": \"fill-extrusion\",\n", - " \"paint\": {\n", - " \"fill-extrusion-color\": [\n", - " \"interpolate\",\n", - " [\"linear\"],\n", - " [\"get\", \"age\"],\n", - " 23.0,\n", - " \"#fff5eb\",\n", - " 24.0,\n", - " \"#fee6ce\",\n", - " 25.0,\n", - " \"#fdd0a2\",\n", - " 26.0,\n", - " \"#fdae6b\",\n", - " 27.0,\n", - " \"#fd8d3c\",\n", - " 28.0,\n", - " \"#f16913\",\n", - " 29.0,\n", - " \"#d94801\",\n", - " 30.0,\n", - " \"#8c2d04\",\n", - " ],\n", - " \"fill-extrusion-opacity\": 1,\n", - " \"fill-extrusion-height\": [\"*\", [\"get\", \"age\"], 5000],\n", - " },\n", - "}\n", - "first_symbol_layer_id = m.find_first_symbol_layer()[\"id\"]\n", - "m.add_layer(layer, first_symbol_layer_id)\n", - "m.add_layer_control()\n", + "m = leafmap.Map(style=\"streets\")\n", "m" ] }, @@ -658,50 +646,19 @@ "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-100, 40], zoom=3, pitch=60, style=\"basic\")\n", - "source = {\n", - " \"type\": \"geojson\",\n", - " \"data\": \"https://open.gishub.org/data/us/us_counties.geojson\",\n", - "}\n", - "m.add_source(\"counties\", source)\n", - "layer = {\n", - " \"id\": \"us-counties\",\n", - " \"source\": \"counties\",\n", - " \"type\": \"fill-extrusion\",\n", - " \"paint\": {\n", - " \"fill-extrusion-color\": [\n", - " \"interpolate\",\n", - " [\"linear\"],\n", - " [\"get\", \"CENSUSAREA\"],\n", - " 400,\n", - " \"#fff5eb\",\n", - " 600,\n", - " \"#fee6ce\",\n", - " 800,\n", - " \"#fdd0a2\",\n", - " 1000,\n", - " \"#fdae6b\",\n", - " ],\n", - " \"fill-extrusion-opacity\": 1,\n", - " \"fill-extrusion-height\": [\"*\", [\"get\", \"CENSUSAREA\"], 50],\n", - " },\n", - "}\n", - "first_symbol_layer_id = m.find_first_symbol_layer()[\"id\"]\n", - "m.add_layer(layer, first_symbol_layer_id)\n", - "m.add_layer_control()\n", + "m = leafmap.Map(style=\"satellite\")\n", "m" ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "id": "50", "metadata": {}, + "outputs": [], "source": [ - "## Visualize vector data\n", - "\n", - "Leafmap provides a variety of methods to visualize vector data on the map.\n", - "\n", - "### Point data" + "m = leafmap.Map(style=\"hybrid\")\n", + "m" ] }, { @@ -711,19 +668,18 @@ "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[12.550343, 55.665957], zoom=8, style=\"positron\")\n", - "m.add_marker(lng_lat=[12.550343, 55.665957])\n", + "m = leafmap.Map(style=\"topo\")\n", "m" ] }, { - "cell_type": "code", - "execution_count": null, + "cell_type": "markdown", "id": "52", "metadata": {}, - "outputs": [], "source": [ - "import requests" + "### Add a vector tile source\n", + "\n", + "To include vector data from MapTiler, first obtain the MapTiler API key and then set up a vector source with the desired tile data URL. The vector tile source can then be added to a layer to display features such as contour lines, which are styled for better visibility and engagement." ] }, { @@ -733,10 +689,7 @@ "metadata": {}, "outputs": [], "source": [ - "url = (\n", - " \"https://github.com/opengeos/datasets/releases/download/world/world_cities.geojson\"\n", - ")\n", - "geojson = requests.get(url).json()" + "MAPTILER_KEY = leafmap.get_api_key(\"MAPTILER_KEY\")" ] }, { @@ -746,43 +699,58 @@ "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(style=\"streets\")\n", - "m.add_geojson(geojson, name=\"cities\")\n", - "m.add_popup(\"cities\")\n", + "m = leafmap.Map(center=[-122.447303, 37.753574], zoom=13, style=\"streets\")\n", + "source = {\n", + " \"type\": \"vector\",\n", + " \"url\": f\"https://api.maptiler.com/tiles/contours/tiles.json?key={MAPTILER_KEY}\",\n", + "}\n", + "layer = {\n", + " \"id\": \"terrain-data\",\n", + " \"type\": \"line\",\n", + " \"source\": \"contours\",\n", + " \"source-layer\": \"contour\",\n", + " \"layout\": {\"line-join\": \"round\", \"line-cap\": \"round\"},\n", + " \"paint\": {\"line-color\": \"#ff69b4\", \"line-width\": 1},\n", + "}\n", + "m.add_source(\"contours\", source)\n", + "m.add_layer(layer)\n", "m" ] }, { - "cell_type": "code", - "execution_count": null, + "cell_type": "markdown", "id": "55", "metadata": {}, - "outputs": [], "source": [ - "m = leafmap.Map(style=\"streets\")\n", - "source = {\"type\": \"geojson\", \"data\": geojson}\n", + "## 3D Mapping\n", "\n", - "layer = {\n", - " \"id\": \"cities\",\n", - " \"type\": \"symbol\",\n", - " \"source\": \"point\",\n", - " \"layout\": {\n", - " \"icon-image\": \"marker_15\",\n", - " \"icon-size\": 1,\n", - " },\n", - "}\n", - "m.add_source(\"point\", source)\n", - "m.add_layer(layer)\n", - "m.add_popup(\"cities\")\n", - "m" + "MapTiler provides a variety of 3D styles that enhance geographic data visualization. Styles can be prefixed with `3d-` to utilize 3D effects such as hybrid, satellite, and topo. The `3d-hillshade` style is used for visualizing hillshade effects alone.\n", + "\n", + "### 3D Terrain\n", + "\n", + "These examples demonstrate different ways to implement 3D terrain visualization:\n", + "\n", + "- **3D Hybrid style**: Adds terrain relief to urban data with hybrid visualization.\n", + "- **3D Satellite style**: Combines satellite imagery with 3D elevation, enhancing visual context for topography.\n", + "- **3D Topo style**: Provides a topographic view with elevation exaggeration and optional hillshade.\n", + "- **3D Terrain style**: Displays terrain with default settings for natural geographic areas.\n", + "- **3D Ocean style**: A specialized terrain style with oceanic details, using exaggeration and hillshade to emphasize depth.\n", + "\n", + "Each terrain map setup includes a pitch and bearing to adjust the map's angle and orientation, giving a better perspective of 3D features." ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "id": "56", "metadata": {}, + "outputs": [], "source": [ - "### Line data" + "m = leafmap.Map(\n", + " center=[-122.1874314, 46.2022386], zoom=13, pitch=60, bearing=220, style=\"3d-hybrid\"\n", + ")\n", + "m.add_layer_control(bg_layers=True)\n", + "m" ] }, { @@ -792,60 +760,35 @@ "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-122.486052, 37.830348], zoom=15, style=\"streets\")\n", - "\n", - "source = {\n", - " \"type\": \"geojson\",\n", - " \"data\": {\n", - " \"type\": \"Feature\",\n", - " \"properties\": {},\n", - " \"geometry\": {\n", - " \"type\": \"LineString\",\n", - " \"coordinates\": [\n", - " [-122.48369693756104, 37.83381888486939],\n", - " [-122.48348236083984, 37.83317489144141],\n", - " [-122.48339653015138, 37.83270036637107],\n", - " [-122.48356819152832, 37.832056363179625],\n", - " [-122.48404026031496, 37.83114119107971],\n", - " [-122.48404026031496, 37.83049717427869],\n", - " [-122.48348236083984, 37.829920943955045],\n", - " [-122.48356819152832, 37.82954808664175],\n", - " [-122.48507022857666, 37.82944639795659],\n", - " [-122.48610019683838, 37.82880236636284],\n", - " [-122.48695850372314, 37.82931081282506],\n", - " [-122.48700141906738, 37.83080223556934],\n", - " [-122.48751640319824, 37.83168351665737],\n", - " [-122.48803138732912, 37.832158048267786],\n", - " [-122.48888969421387, 37.83297152392784],\n", - " [-122.48987674713133, 37.83263257682617],\n", - " [-122.49043464660643, 37.832937629287755],\n", - " [-122.49125003814696, 37.832429207817725],\n", - " [-122.49163627624512, 37.832564787218985],\n", - " [-122.49223709106445, 37.83337825839438],\n", - " [-122.49378204345702, 37.83368330777276],\n", - " ],\n", - " },\n", - " },\n", - "}\n", - "\n", - "layer = {\n", - " \"id\": \"route\",\n", - " \"type\": \"line\",\n", - " \"source\": \"route\",\n", - " \"layout\": {\"line-join\": \"round\", \"line-cap\": \"round\"},\n", - " \"paint\": {\"line-color\": \"#888\", \"line-width\": 8},\n", - "}\n", - "m.add_source(\"route\", source)\n", - "m.add_layer(layer)\n", + "m = leafmap.Map(\n", + " center=[-122.1874314, 46.2022386],\n", + " zoom=13,\n", + " pitch=60,\n", + " bearing=220,\n", + " style=\"3d-satellite\",\n", + ")\n", + "m.add_layer_control(bg_layers=True)\n", "m" ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "id": "58", "metadata": {}, + "outputs": [], "source": [ - "### Polygon data" + "m = leafmap.Map(\n", + " center=[-122.1874314, 46.2022386],\n", + " zoom=13,\n", + " pitch=60,\n", + " bearing=220,\n", + " style=\"3d-topo\",\n", + " exaggeration=1.5,\n", + " hillshade=False,\n", + ")\n", + "m.add_layer_control(bg_layers=True)\n", + "m" ] }, { @@ -855,329 +798,1810 @@ "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-68.137343, 45.137451], zoom=5, style=\"streets\")\n", - "geojson = {\n", - " \"type\": \"Feature\",\n", - " \"geometry\": {\n", - " \"type\": \"Polygon\",\n", - " \"coordinates\": [\n", - " [\n", - " [-67.13734351262877, 45.137451890638886],\n", - " [-66.96466, 44.8097],\n", - " [-68.03252, 44.3252],\n", - " [-69.06, 43.98],\n", - " [-70.11617, 43.68405],\n", - " [-70.64573401557249, 43.090083319667144],\n", - " [-70.75102474636725, 43.08003225358635],\n", - " [-70.79761105007827, 43.21973948828747],\n", - " [-70.98176001655037, 43.36789581966826],\n", - " [-70.94416541205806, 43.46633942318431],\n", - " [-71.08482, 45.3052400000002],\n", - " [-70.6600225491012, 45.46022288673396],\n", - " [-70.30495378282376, 45.914794623389355],\n", - " [-70.00014034695016, 46.69317088478567],\n", - " [-69.23708614772835, 47.44777598732787],\n", - " [-68.90478084987546, 47.184794623394396],\n", - " [-68.23430497910454, 47.35462921812177],\n", - " [-67.79035274928509, 47.066248887716995],\n", - " [-67.79141211614706, 45.702585354182816],\n", - " [-67.13734351262877, 45.137451890638886],\n", - " ]\n", - " ],\n", - " },\n", + "m = leafmap.Map(\n", + " center=[-122.1874314, 46.2022386],\n", + " zoom=13,\n", + " pitch=60,\n", + " bearing=220,\n", + " style=\"3d-terrain\",\n", + ")\n", + "m.add_layer_control(bg_layers=True)\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "60", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(style=\"3d-ocean\", exaggeration=1.5, hillshade=True)\n", + "m.add_layer_control(bg_layers=True)\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "61", + "metadata": {}, + "source": [ + "### 3D Buildings\n", + "\n", + "Adding 3D buildings enhances urban visualizations, showing buildings with height variations. The setup involves specifying the MapTiler API key for vector tiles and adding building data as a 3D extrusion layer. The extrusion height and color can be set based on data attributes to visualize structures with varying heights, which can be useful in city planning and urban analysis." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "62", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(\n", + " center=[-74.01201, 40.70473], zoom=16, pitch=60, bearing=35, style=\"basic-v2\"\n", + ")\n", + "MAPTILER_KEY = leafmap.get_api_key(\"MAPTILER_KEY\")\n", + "m.add_basemap(\"Esri.WorldImagery\", visible=False)\n", + "source = {\n", + " \"url\": f\"https://api.maptiler.com/tiles/v3/tiles.json?key={MAPTILER_KEY}\",\n", + " \"type\": \"vector\",\n", "}\n", - "source = {\"type\": \"geojson\", \"data\": geojson}\n", - "m.add_source(\"maine\", source)\n", + "\n", "layer = {\n", - " \"id\": \"maine\",\n", - " \"type\": \"fill\",\n", - " \"source\": \"maine\",\n", - " \"layout\": {},\n", - " \"paint\": {\"fill-color\": \"#088\", \"fill-opacity\": 0.8},\n", + " \"id\": \"3d-buildings\",\n", + " \"source\": \"openmaptiles\",\n", + " \"source-layer\": \"building\",\n", + " \"type\": \"fill-extrusion\",\n", + " \"min-zoom\": 15,\n", + " \"paint\": {\n", + " \"fill-extrusion-color\": [\n", + " \"interpolate\",\n", + " [\"linear\"],\n", + " [\"get\", \"render_height\"],\n", + " 0,\n", + " \"lightgray\",\n", + " 200,\n", + " \"royalblue\",\n", + " 400,\n", + " \"lightblue\",\n", + " ],\n", + " \"fill-extrusion-height\": [\n", + " \"interpolate\",\n", + " [\"linear\"],\n", + " [\"zoom\"],\n", + " 15,\n", + " 0,\n", + " 16,\n", + " [\"get\", \"render_height\"],\n", + " ],\n", + " \"fill-extrusion-base\": [\n", + " \"case\",\n", + " [\">=\", [\"get\", \"zoom\"], 16],\n", + " [\"get\", \"render_min_height\"],\n", + " 0,\n", + " ],\n", + " },\n", "}\n", + "m.add_source(\"openmaptiles\", source)\n", "m.add_layer(layer)\n", + "m.add_layer_control()\n", "m" ] }, { "cell_type": "code", "execution_count": null, - "id": "60", + "id": "63", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-68.137343, 45.137451], zoom=5, style=\"streets\")\n", - "paint = {\"fill-color\": \"#088\", \"fill-opacity\": 0.8}\n", - "m.add_geojson(geojson, layer_type=\"fill\", paint=paint)\n", + "m = leafmap.Map(\n", + " center=[-74.01201, 40.70473], zoom=16, pitch=60, bearing=35, style=\"basic-v2\"\n", + ")\n", + "m.add_basemap(\"Esri.WorldImagery\", visible=False)\n", + "m.add_3d_buildings(min_zoom=15)\n", + "m.add_layer_control()\n", "m" ] }, { "cell_type": "markdown", - "id": "61", + "id": "64", "metadata": {}, "source": [ - "### Multiple geometries" + "### 3D Indoor Mapping\n", + "\n", + "Indoor mapping data can be visualized by loading a GeoJSON file and applying the `add_geojson` method. This setup allows for displaying floorplans with attributes such as color, height, and opacity. It provides a realistic indoor perspective, which is useful for visualizing complex structures or navigating interior spaces." ] }, { "cell_type": "code", "execution_count": null, - "id": "62", + "id": "65", + "metadata": {}, + "outputs": [], + "source": [ + "data = \"https://maplibre.org/maplibre-gl-js/docs/assets/indoor-3d-map.geojson\"\n", + "gdf = leafmap.geojson_to_gdf(data)\n", + "gdf.explore()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "66", + "metadata": {}, + "outputs": [], + "source": [ + "gdf.head()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "67", "metadata": {}, "outputs": [], "source": [ "m = leafmap.Map(\n", - " center=[-123.13, 49.254], zoom=11, style=\"dark-matter\", pitch=45, bearing=0\n", + " center=(-87.61694, 41.86625), zoom=17, pitch=40, bearing=20, style=\"positron\"\n", ")\n", - "url = \"https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/geojson/vancouver-blocks.json\"\n", - "paint_line = {\n", - " \"line-color\": \"white\",\n", - " \"line-width\": 2,\n", + "m.add_basemap(\"OpenStreetMap.Mapnik\")\n", + "m.add_geojson(\n", + " data,\n", + " layer_type=\"fill-extrusion\",\n", + " name=\"floorplan\",\n", + " paint={\n", + " \"fill-extrusion-color\": [\"get\", \"color\"],\n", + " \"fill-extrusion-height\": [\"get\", \"height\"],\n", + " \"fill-extrusion-base\": [\"get\", \"base_height\"],\n", + " \"fill-extrusion-opacity\": 0.5,\n", + " },\n", + ")\n", + "m.add_layer_control()\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "68", + "metadata": {}, + "source": [ + "### 3D Choropleth Map\n", + "\n", + "Choropleth maps in 3D allow visualizing attribute data by height, where regions are colored and extruded based on specific attributes, such as age or population area. Two examples are provided below:\n", + "\n", + "- **European Countries (Age at First Marriage)**: The map displays different colors and extrusion heights based on age data. Color interpolations help represent data variations across regions, making it a suitable map for demographic studies.\n", + "\n", + "- **US Counties (Census Area)**: This example uses census data to display county areas in the United States, where each county’s area is represented with a different color and height based on its size. This type of map provides insights into geographic distribution and area proportions across the region.\n", + "\n", + "Both maps use a fill-extrusion style to dynamically adjust color and height, creating a 3D effect that enhances data interpretation." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "69", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[19.43, 49.49], zoom=3, pitch=60, style=\"basic\")\n", + "source = {\n", + " \"type\": \"geojson\",\n", + " \"data\": \"https://docs.maptiler.com/sdk-js/assets/Mean_age_of_women_at_first_marriage_in_2019.geojson\",\n", "}\n", - "paint_fill = {\n", - " \"fill-extrusion-color\": {\n", - " \"property\": \"valuePerSqm\",\n", - " \"stops\": [\n", - " [0, \"grey\"],\n", - " [1000, \"yellow\"],\n", - " [5000, \"orange\"],\n", - " [10000, \"darkred\"],\n", - " [50000, \"lightblue\"],\n", + "m.add_source(\"countries\", source)\n", + "layer = {\n", + " \"id\": \"eu-countries\",\n", + " \"source\": \"countries\",\n", + " \"type\": \"fill-extrusion\",\n", + " \"paint\": {\n", + " \"fill-extrusion-color\": [\n", + " \"interpolate\",\n", + " [\"linear\"],\n", + " [\"get\", \"age\"],\n", + " 23.0,\n", + " \"#fff5eb\",\n", + " 24.0,\n", + " \"#fee6ce\",\n", + " 25.0,\n", + " \"#fdd0a2\",\n", + " 26.0,\n", + " \"#fdae6b\",\n", + " 27.0,\n", + " \"#fd8d3c\",\n", + " 28.0,\n", + " \"#f16913\",\n", + " 29.0,\n", + " \"#d94801\",\n", + " 30.0,\n", + " \"#8c2d04\",\n", " ],\n", + " \"fill-extrusion-opacity\": 1,\n", + " \"fill-extrusion-height\": [\"*\", [\"get\", \"age\"], 5000],\n", " },\n", - " \"fill-extrusion-height\": [\"*\", 10, [\"sqrt\", [\"get\", \"valuePerSqm\"]]],\n", - " \"fill-extrusion-opacity\": 0.9,\n", "}\n", - "m.add_geojson(url, layer_type=\"line\", paint=paint_line, name=\"blocks-line\")\n", - "m.add_geojson(url, layer_type=\"fill-extrusion\", paint=paint_fill, name=\"blocks-fill\")\n", + "first_symbol_layer_id = m.find_first_symbol_layer()[\"id\"]\n", + "m.add_layer(layer, first_symbol_layer_id)\n", + "m.add_layer_control()\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "70", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-100, 40], zoom=3, pitch=60, style=\"basic\")\n", + "source = {\n", + " \"type\": \"geojson\",\n", + " \"data\": \"https://open.gishub.org/data/us/us_counties.geojson\",\n", + "}\n", + "m.add_source(\"counties\", source)\n", + "layer = {\n", + " \"id\": \"us-counties\",\n", + " \"source\": \"counties\",\n", + " \"type\": \"fill-extrusion\",\n", + " \"paint\": {\n", + " \"fill-extrusion-color\": [\n", + " \"interpolate\",\n", + " [\"linear\"],\n", + " [\"get\", \"CENSUSAREA\"],\n", + " 400,\n", + " \"#fff5eb\",\n", + " 600,\n", + " \"#fee6ce\",\n", + " 800,\n", + " \"#fdd0a2\",\n", + " 1000,\n", + " \"#fdae6b\",\n", + " ],\n", + " \"fill-extrusion-opacity\": 1,\n", + " \"fill-extrusion-height\": [\"*\", [\"get\", \"CENSUSAREA\"], 50],\n", + " },\n", + "}\n", + "first_symbol_layer_id = m.find_first_symbol_layer()[\"id\"]\n", + "m.add_layer(layer, first_symbol_layer_id)\n", + "m.add_layer_control()\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "71", + "metadata": {}, + "source": [ + "## Visualize Vector Data\n", + "\n", + "Leafmap provides a variety of methods to visualize vector data on a map, allowing you to display points, lines, polygons, and other vector shapes with custom styling and interactivity.\n", + "\n", + "### Point Data\n", + "\n", + "The following examples demonstrate how to display points on the map.\n", + "\n", + "- **Simple Marker**: Initializes the map centered on a specific latitude and longitude, then adds a static marker to the location.\n", + "\n", + "- **Draggable Marker**: Similar to the simple marker, but with an additional option to make the marker draggable. This allows users to reposition it directly on the map.\n", + "\n", + "- **Multiple Points with GeoJSON**: Loads point data from a GeoJSON file containing world city locations. After reading the data, it’s added to the map as a layer named “cities.” Popups can be enabled to display additional information when a user clicks on a city.\n", + "\n", + "- **Custom Symbol Layer**: Loads point data as symbols instead of markers and customizes the symbol layout using icons, which can be scaled to any size." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "72", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[12.550343, 55.665957], zoom=8, style=\"positron\")\n", + "m.add_marker(lng_lat=[12.550343, 55.665957])\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "73", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[12.550343, 55.665957], zoom=8, style=\"positron\")\n", + "m.add_marker(lng_lat=[12.550343, 55.665957], options={\"draggable\": True})\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "74", + "metadata": {}, + "outputs": [], + "source": [ + "url = (\n", + " \"https://github.com/opengeos/datasets/releases/download/world/world_cities.geojson\"\n", + ")\n", + "geojson = leafmap.read_geojson(url)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "75", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(style=\"streets\")\n", + "m.add_geojson(geojson, name=\"cities\")\n", + "m.add_popup(\"cities\")\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "76", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(style=\"streets\")\n", + "source = {\"type\": \"geojson\", \"data\": geojson}\n", + "\n", + "layer = {\n", + " \"id\": \"cities\",\n", + " \"type\": \"symbol\",\n", + " \"source\": \"point\",\n", + " \"layout\": {\n", + " \"icon-image\": \"marker_15\",\n", + " \"icon-size\": 1,\n", + " },\n", + "}\n", + "m.add_source(\"point\", source)\n", + "m.add_layer(layer)\n", + "m.add_popup(\"cities\")\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "77", + "metadata": {}, + "source": [ + "### Customize Marker Icon Image\n", + "\n", + "To further customize point data, an image icon can be used instead of the default marker:\n", + "\n", + "- **Add Custom Icon**: Loads an OSGeo logo as the custom marker image. The GeoJSON source for conference locations is loaded, and each location is marked with the custom icon and labeled with the year. Layout options define the placement of text and icons." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "78", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[0, 0], zoom=1, style=\"positron\")\n", + "image = \"https://maplibre.org/maplibre-gl-js/docs/assets/osgeo-logo.png\"\n", + "m.add_image(\"custom-marker\", image)\n", + "\n", + "url = \"https://github.com/opengeos/datasets/releases/download/places/osgeo_conferences.geojson\"\n", + "geojson = leafmap.read_geojson(url)\n", + "\n", + "source = {\"type\": \"geojson\", \"data\": geojson}\n", + "\n", + "m.add_source(\"conferences\", source)\n", + "layer = {\n", + " \"id\": \"conferences\",\n", + " \"type\": \"symbol\",\n", + " \"source\": \"conferences\",\n", + " \"layout\": {\n", + " \"icon-image\": \"custom-marker\",\n", + " \"text-field\": [\"get\", \"year\"],\n", + " \"text-font\": [\"Open Sans Semibold\", \"Arial Unicode MS Bold\"],\n", + " \"text-offset\": [0, 1.25],\n", + " \"text-anchor\": \"top\",\n", + " },\n", + "}\n", + "\n", + "m.add_layer(layer)\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "79", + "metadata": {}, + "source": [ + "### Line Data\n", + "\n", + "Lines can be displayed to represent routes, boundaries, or connections between locations:\n", + "\n", + "- **Basic Line**: Sets up a line with multiple coordinates to create a path. The map displays this path with rounded line joins and a defined color and width, giving it a polished appearance." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "80", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-122.486052, 37.830348], zoom=15, style=\"streets\")\n", + "\n", + "source = {\n", + " \"type\": \"geojson\",\n", + " \"data\": {\n", + " \"type\": \"Feature\",\n", + " \"properties\": {},\n", + " \"geometry\": {\n", + " \"type\": \"LineString\",\n", + " \"coordinates\": [\n", + " [-122.48369693756104, 37.83381888486939],\n", + " [-122.48348236083984, 37.83317489144141],\n", + " [-122.48339653015138, 37.83270036637107],\n", + " [-122.48356819152832, 37.832056363179625],\n", + " [-122.48404026031496, 37.83114119107971],\n", + " [-122.48404026031496, 37.83049717427869],\n", + " [-122.48348236083984, 37.829920943955045],\n", + " [-122.48356819152832, 37.82954808664175],\n", + " [-122.48507022857666, 37.82944639795659],\n", + " [-122.48610019683838, 37.82880236636284],\n", + " [-122.48695850372314, 37.82931081282506],\n", + " [-122.48700141906738, 37.83080223556934],\n", + " [-122.48751640319824, 37.83168351665737],\n", + " [-122.48803138732912, 37.832158048267786],\n", + " [-122.48888969421387, 37.83297152392784],\n", + " [-122.48987674713133, 37.83263257682617],\n", + " [-122.49043464660643, 37.832937629287755],\n", + " [-122.49125003814696, 37.832429207817725],\n", + " [-122.49163627624512, 37.832564787218985],\n", + " [-122.49223709106445, 37.83337825839438],\n", + " [-122.49378204345702, 37.83368330777276],\n", + " ],\n", + " },\n", + " },\n", + "}\n", + "\n", + "layer = {\n", + " \"id\": \"route\",\n", + " \"type\": \"line\",\n", + " \"source\": \"route\",\n", + " \"layout\": {\"line-join\": \"round\", \"line-cap\": \"round\"},\n", + " \"paint\": {\"line-color\": \"#888\", \"line-width\": 8},\n", + "}\n", + "m.add_source(\"route\", source)\n", + "m.add_layer(layer)\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "81", + "metadata": {}, + "source": [ + "### Polygon Data\n", + "\n", + "Polygons represent regions or areas on the map. Leafmap offers options to display filled polygons with customizable colors and opacities.\n", + "\n", + "- **Basic Polygon**: Adds a GeoJSON polygon representing an area and customizes its fill color and opacity.\n", + "\n", + "- **Outlined Polygon**: In addition to filling the polygon, an outline color is specified to highlight the polygon’s boundary. Both fill and line layers are defined, enhancing visual clarity.\n", + "\n", + "- **Building Visualization with GeoJSON**: Uses a URL to load building data and displays it with a customized fill color and outline. The style uses a hybrid map view for additional context." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "82", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-68.137343, 45.137451], zoom=5, style=\"streets\")\n", + "geojson = {\n", + " \"type\": \"Feature\",\n", + " \"geometry\": {\n", + " \"type\": \"Polygon\",\n", + " \"coordinates\": [\n", + " [\n", + " [-67.13734351262877, 45.137451890638886],\n", + " [-66.96466, 44.8097],\n", + " [-68.03252, 44.3252],\n", + " [-69.06, 43.98],\n", + " [-70.11617, 43.68405],\n", + " [-70.64573401557249, 43.090083319667144],\n", + " [-70.75102474636725, 43.08003225358635],\n", + " [-70.79761105007827, 43.21973948828747],\n", + " [-70.98176001655037, 43.36789581966826],\n", + " [-70.94416541205806, 43.46633942318431],\n", + " [-71.08482, 45.3052400000002],\n", + " [-70.6600225491012, 45.46022288673396],\n", + " [-70.30495378282376, 45.914794623389355],\n", + " [-70.00014034695016, 46.69317088478567],\n", + " [-69.23708614772835, 47.44777598732787],\n", + " [-68.90478084987546, 47.184794623394396],\n", + " [-68.23430497910454, 47.35462921812177],\n", + " [-67.79035274928509, 47.066248887716995],\n", + " [-67.79141211614706, 45.702585354182816],\n", + " [-67.13734351262877, 45.137451890638886],\n", + " ]\n", + " ],\n", + " },\n", + "}\n", + "source = {\"type\": \"geojson\", \"data\": geojson}\n", + "m.add_source(\"maine\", source)\n", + "layer = {\n", + " \"id\": \"maine\",\n", + " \"type\": \"fill\",\n", + " \"source\": \"maine\",\n", + " \"layout\": {},\n", + " \"paint\": {\"fill-color\": \"#088\", \"fill-opacity\": 0.8},\n", + "}\n", + "m.add_layer(layer)\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "83", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-68.137343, 45.137451], zoom=5, style=\"streets\")\n", + "paint = {\"fill-color\": \"#088\", \"fill-opacity\": 0.8}\n", + "m.add_geojson(geojson, layer_type=\"fill\", paint=paint)\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "84", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(style=\"hybrid\")\n", + "geojson = \"https://github.com/opengeos/datasets/releases/download/places/wa_overture_buildings.geojson\"\n", + "paint = {\"fill-color\": \"#ffff00\", \"fill-opacity\": 0.5, \"fill-outline-color\": \"#ff0000\"}\n", + "m.add_geojson(geojson, layer_type=\"fill\", paint=paint, name=\"Fill\")\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "85", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(style=\"hybrid\")\n", + "geojson = \"https://github.com/opengeos/datasets/releases/download/places/wa_overture_buildings.geojson\"\n", + "paint_line = {\"line-color\": \"#ff0000\", \"line-width\": 3}\n", + "m.add_geojson(geojson, layer_type=\"line\", paint=paint_line, name=\"Outline\")\n", + "paint_fill = {\"fill-color\": \"#ffff00\", \"fill-opacity\": 0.5}\n", + "m.add_geojson(geojson, layer_type=\"fill\", paint=paint_fill, name=\"Fill\")\n", + "m.add_layer_control()\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "86", + "metadata": {}, + "source": [ + "### Multiple Geometries\n", + "\n", + "This example displays both line and extrusion fills for complex data types:\n", + "\n", + "- **Extruded Blocks with Line Overlay**: Loads Vancouver building blocks data and applies both line and fill-extrusion styles. Each block’s height is based on an attribute, which provides a 3D effect. This is useful for visualizing value distribution across an urban landscape." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "87", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(\n", + " center=[-123.13, 49.254], zoom=11, style=\"dark-matter\", pitch=45, bearing=0\n", + ")\n", + "url = \"https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/geojson/vancouver-blocks.json\"\n", + "paint_line = {\n", + " \"line-color\": \"white\",\n", + " \"line-width\": 2,\n", + "}\n", + "paint_fill = {\n", + " \"fill-extrusion-color\": {\n", + " \"property\": \"valuePerSqm\",\n", + " \"stops\": [\n", + " [0, \"grey\"],\n", + " [1000, \"yellow\"],\n", + " [5000, \"orange\"],\n", + " [10000, \"darkred\"],\n", + " [50000, \"lightblue\"],\n", + " ],\n", + " },\n", + " \"fill-extrusion-height\": [\"*\", 10, [\"sqrt\", [\"get\", \"valuePerSqm\"]]],\n", + " \"fill-extrusion-opacity\": 0.9,\n", + "}\n", + "m.add_geojson(url, layer_type=\"line\", paint=paint_line, name=\"blocks-line\")\n", + "m.add_geojson(url, layer_type=\"fill-extrusion\", paint=paint_fill, name=\"blocks-fill\")\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "88", + "metadata": {}, + "outputs": [], + "source": [ + "m.layer_interact()" + ] + }, + { + "cell_type": "markdown", + "id": "89", + "metadata": {}, + "source": [ + "### Marker Cluster\n", + "\n", + "Clusters help manage large datasets, such as earthquake data, by grouping nearby markers. The color and size of clusters change based on the point count, and filters differentiate individual points from clusters. This example uses nested GeoJSON layers for visualizing clustered earthquake occurrences, with separate styles for individual points and clusters." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "90", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-103.59179, 40.66995], zoom=3, style=\"streets\")\n", + "data = \"https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson\"\n", + "source_args = {\n", + " \"cluster\": True,\n", + " \"cluster_radius\": 50,\n", + " \"cluster_min_points\": 2,\n", + " \"cluster_max_zoom\": 14,\n", + " \"cluster_properties\": {\n", + " \"maxMag\": [\"max\", [\"get\", \"mag\"]],\n", + " \"minMag\": [\"min\", [\"get\", \"mag\"]],\n", + " },\n", + "}\n", + "\n", + "m.add_geojson(\n", + " data,\n", + " layer_type=\"circle\",\n", + " name=\"earthquake-circles\",\n", + " filter=[\"!\", [\"has\", \"point_count\"]],\n", + " paint={\"circle-color\": \"darkblue\"},\n", + " source_args=source_args,\n", + ")\n", + "\n", + "m.add_geojson(\n", + " data,\n", + " layer_type=\"circle\",\n", + " name=\"earthquake-clusters\",\n", + " filter=[\"has\", \"point_count\"],\n", + " paint={\n", + " \"circle-color\": [\n", + " \"step\",\n", + " [\"get\", \"point_count\"],\n", + " \"#51bbd6\",\n", + " 100,\n", + " \"#f1f075\",\n", + " 750,\n", + " \"#f28cb1\",\n", + " ],\n", + " \"circle-radius\": [\"step\", [\"get\", \"point_count\"], 20, 100, 30, 750, 40],\n", + " },\n", + " source_args=source_args,\n", + ")\n", + "\n", + "m.add_geojson(\n", + " data,\n", + " layer_type=\"symbol\",\n", + " name=\"earthquake-labels\",\n", + " filter=[\"has\", \"point_count\"],\n", + " layout={\n", + " \"text-field\": [\"get\", \"point_count_abbreviated\"],\n", + " \"text-size\": 12,\n", + " },\n", + " source_args=source_args,\n", + ")\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "91", + "metadata": {}, + "source": [ + "### Local Vector Data\n", + "\n", + "Local vector files, such as GeoJSON, can be loaded directly into the map. The example downloads a GeoJSON file representing U.S. states and adds it to the map using `open_geojson`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "92", + "metadata": {}, + "outputs": [], + "source": [ + "url = \"https://github.com/opengeos/datasets/releases/download/us/us_states.geojson\"\n", + "filepath = \"data/us_states.geojson\"\n", + "leafmap.download_file(url, filepath, quiet=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "93", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-100, 40], zoom=3)\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "94", + "metadata": {}, + "outputs": [], + "source": [ + "m.open_geojson()" + ] + }, + { + "cell_type": "markdown", + "id": "95", + "metadata": {}, + "source": [ + "### Local Vector Data\n", + "\n", + "Local vector files, such as GeoJSON, can be loaded directly into the map. The example downloads a GeoJSON file representing U.S. states and adds it to the map using `open_geojson`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "96", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"streets\")\n", + "url = \"https://github.com/opengeos/datasets/releases/download/us/us_states.geojson\"\n", + "gdf = leafmap.geojson_to_gdf(url)\n", + "paint = {\n", + " \"fill-color\": \"#3388ff\",\n", + " \"fill-opacity\": 0.8,\n", + " \"fill-outline-color\": \"#ffffff\",\n", + "}\n", + "m.add_gdf(gdf, layer_type=\"fill\", name=\"States\", paint=paint)\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "97", + "metadata": {}, + "source": [ + "### Change Building Color\n", + "\n", + "You can customize the color and opacity of buildings based on the map’s zoom level. This example changes building colors from orange at lower zoom levels to lighter shades as the zoom level increases. Additionally, the opacity gradually transitions to fully opaque, making buildings more visible at close-up zoom levels." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "98", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-90.73414, 14.55524], zoom=13, style=\"basic\")\n", + "m.set_paint_property(\n", + " \"building\",\n", + " \"fill-color\",\n", + " [\"interpolate\", [\"exponential\", 0.5], [\"zoom\"], 15, \"#e2714b\", 22, \"#eee695\"],\n", + ")\n", + "m.set_paint_property(\n", + " \"building\",\n", + " \"fill-opacity\",\n", + " [\"interpolate\", [\"exponential\", 0.5], [\"zoom\"], 15, 0, 22, 1],\n", + ")\n", + "m.add_layer_control(bg_layers=True)\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "99", + "metadata": {}, + "outputs": [], + "source": [ + "m.add_call(\"zoomTo\", 19, {\"duration\": 9000})" + ] + }, + { + "cell_type": "markdown", + "id": "100", + "metadata": {}, + "source": [ + "### Add a New Layer Below Labels\n", + "\n", + "A layer can be added below existing labels on the map to enhance clarity without obscuring labels. The urban areas dataset is displayed as a fill layer in a color and opacity that visually distinguishes it from other map elements. The layer is positioned below symbols, allowing place names to remain visible." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "101", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-88.137343, 35.137451], zoom=4, style=\"streets\")\n", + "source = {\n", + " \"type\": \"geojson\",\n", + " \"data\": \"https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_50m_urban_areas.geojson\",\n", + "}\n", + "m.add_source(\"urban-areas\", source)\n", + "first_symbol_layer = m.find_first_symbol_layer()\n", + "layer = {\n", + " \"id\": \"urban-areas-fill\",\n", + " \"type\": \"fill\",\n", + " \"source\": \"urban-areas\",\n", + " \"layout\": {},\n", + " \"paint\": {\"fill-color\": \"#f08\", \"fill-opacity\": 0.4},\n", + "}\n", + "m.add_layer(layer, before_id=first_symbol_layer[\"id\"])\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "102", + "metadata": {}, + "source": [ + "### Heat Map\n", + "\n", + "Heatmaps visually represent data density. This example uses earthquake data and configures the heatmap layer with dynamic properties, such as weight, intensity, color, and radius, based on earthquake magnitudes. Circles are added to indicate individual earthquakes, with colors and sizes varying according to their magnitude." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "103", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-120, 50], zoom=2, style=\"basic\")\n", + "source = {\n", + " \"type\": \"geojson\",\n", + " \"data\": \"https://maplibre.org/maplibre-gl-js/docs/assets/earthquakes.geojson\",\n", + "}\n", + "m.add_source(\"earthquakes\", source)\n", + "layer = {\n", + " \"id\": \"earthquakes-heat\",\n", + " \"type\": \"heatmap\",\n", + " \"source\": \"earthquakes\",\n", + " \"maxzoom\": 9,\n", + " \"paint\": {\n", + " # Increase the heatmap weight based on frequency and property magnitude\n", + " \"heatmap-weight\": [\"interpolate\", [\"linear\"], [\"get\", \"mag\"], 0, 0, 6, 1],\n", + " # Increase the heatmap color weight weight by zoom level\n", + " # heatmap-intensity is a multiplier on top of heatmap-weight\n", + " \"heatmap-intensity\": [\"interpolate\", [\"linear\"], [\"zoom\"], 0, 1, 9, 3],\n", + " # Color ramp for heatmap. Domain is 0 (low) to 1 (high).\n", + " # Begin color ramp at 0-stop with a 0-transparency color\n", + " # to create a blur-like effect.\n", + " \"heatmap-color\": [\n", + " \"interpolate\",\n", + " [\"linear\"],\n", + " [\"heatmap-density\"],\n", + " 0,\n", + " \"rgba(33,102,172,0)\",\n", + " 0.2,\n", + " \"rgb(103,169,207)\",\n", + " 0.4,\n", + " \"rgb(209,229,240)\",\n", + " 0.6,\n", + " \"rgb(253,219,199)\",\n", + " 0.8,\n", + " \"rgb(239,138,98)\",\n", + " 1,\n", + " \"rgb(178,24,43)\",\n", + " ],\n", + " # Adjust the heatmap radius by zoom level\n", + " \"heatmap-radius\": [\"interpolate\", [\"linear\"], [\"zoom\"], 0, 2, 9, 20],\n", + " # Transition from heatmap to circle layer by zoom level\n", + " \"heatmap-opacity\": [\"interpolate\", [\"linear\"], [\"zoom\"], 7, 1, 9, 0],\n", + " },\n", + "}\n", + "m.add_layer(layer, before_id=\"waterway\")\n", + "layer2 = {\n", + " \"id\": \"earthquakes-point\",\n", + " \"type\": \"circle\",\n", + " \"source\": \"earthquakes\",\n", + " \"minzoom\": 7,\n", + " \"paint\": {\n", + " # Size circle radius by earthquake magnitude and zoom level\n", + " \"circle-radius\": [\n", + " \"interpolate\",\n", + " [\"linear\"],\n", + " [\"zoom\"],\n", + " 7,\n", + " [\"interpolate\", [\"linear\"], [\"get\", \"mag\"], 1, 1, 6, 4],\n", + " 16,\n", + " [\"interpolate\", [\"linear\"], [\"get\", \"mag\"], 1, 5, 6, 50],\n", + " ],\n", + " # Color circle by earthquake magnitude\n", + " \"circle-color\": [\n", + " \"interpolate\",\n", + " [\"linear\"],\n", + " [\"get\", \"mag\"],\n", + " 1,\n", + " \"rgba(33,102,172,0)\",\n", + " 2,\n", + " \"rgb(103,169,207)\",\n", + " 3,\n", + " \"rgb(209,229,240)\",\n", + " 4,\n", + " \"rgb(253,219,199)\",\n", + " 5,\n", + " \"rgb(239,138,98)\",\n", + " 6,\n", + " \"rgb(178,24,43)\",\n", + " ],\n", + " \"circle-stroke-color\": \"white\",\n", + " \"circle-stroke-width\": 1,\n", + " # Transition from heatmap to circle layer by zoom level\n", + " \"circle-opacity\": [\"interpolate\", [\"linear\"], [\"zoom\"], 7, 0, 8, 1],\n", + " },\n", + "}\n", + "m.add_layer(layer2, before_id=\"waterway\")\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "104", + "metadata": {}, + "source": [ + "### Visualize Population Density\n", + "\n", + "Population density can be calculated and displayed dynamically. This example loads a GeoJSON of Rwandan provinces, calculating density by dividing population by area. The fill color of each province is then adjusted based on density, with different color schemes applied depending on the zoom level." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "105", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[30.0222, -1.9596], zoom=7, style=\"streets\")\n", + "source = {\n", + " \"type\": \"geojson\",\n", + " \"data\": \"https://maplibre.org/maplibre-gl-js/docs/assets/rwanda-provinces.geojson\",\n", + "}\n", + "m.add_source(\"rwanda-provinces\", source)\n", + "layer = {\n", + " \"id\": \"rwanda-provinces\",\n", + " \"type\": \"fill\",\n", + " \"source\": \"rwanda-provinces\",\n", + " \"layout\": {},\n", + " \"paint\": {\n", + " \"fill-color\": [\n", + " \"let\",\n", + " \"density\",\n", + " [\"/\", [\"get\", \"population\"], [\"get\", \"sq-km\"]],\n", + " [\n", + " \"interpolate\",\n", + " [\"linear\"],\n", + " [\"zoom\"],\n", + " 8,\n", + " [\n", + " \"interpolate\",\n", + " [\"linear\"],\n", + " [\"var\", \"density\"],\n", + " 274,\n", + " [\"to-color\", \"#edf8e9\"],\n", + " 1551,\n", + " [\"to-color\", \"#006d2c\"],\n", + " ],\n", + " 10,\n", + " [\n", + " \"interpolate\",\n", + " [\"linear\"],\n", + " [\"var\", \"density\"],\n", + " 274,\n", + " [\"to-color\", \"#eff3ff\"],\n", + " 1551,\n", + " [\"to-color\", \"#08519c\"],\n", + " ],\n", + " ],\n", + " ],\n", + " \"fill-opacity\": 0.7,\n", + " },\n", + "}\n", + "m.add_layer(layer)\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "106", + "metadata": {}, + "source": [ + "## Visualize Raster Data\n", + "\n", + "### Local Raster Data\n", + "\n", + "To visualize local raster files, use the `add_raster` method. In the example, a Landsat image is downloaded and displayed using two different band combinations:\n", + "\n", + "- **Band Combination 3-2-1 (True Color)**: Simulates natural colors in the RGB channels.\n", + "- **Band Combination 4-3-2**: Enhances vegetation, displaying it in red for better visual contrast.\n", + "These layers are added to the map along with controls to toggle them. You can adjust brightness and contrast with the `vmin` and `vmax` arguments to improve clarity." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "107", + "metadata": {}, + "outputs": [], + "source": [ + "url = \"https://github.com/opengeos/datasets/releases/download/raster/landsat.tif\"\n", + "filepath = \"landsat.tif\"\n", + "leafmap.download_file(url, filepath, quiet=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "108", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(style=\"streets\")\n", + "m.add_raster(filepath, indexes=[3, 2, 1], vmin=0, vmax=100, name=\"Landsat-321\")\n", + "m.add_raster(filepath, indexes=[4, 3, 2], vmin=0, vmax=100, name=\"Landsat-432\")\n", + "m.add_layer_control()\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "109", + "metadata": {}, + "outputs": [], + "source": [ + "m.layer_interact()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "110", + "metadata": {}, + "outputs": [], + "source": [ + "url = \"https://github.com/opengeos/datasets/releases/download/raster/srtm90.tif\"\n", + "filepath = \"srtm90.tif\"\n", + "leafmap.download_file(url, filepath, quiet=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "111", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(style=\"satellite\")\n", + "m.add_raster(filepath, colormap=\"terrain\", name=\"DEM\")\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "112", + "metadata": {}, + "source": [ + "A Digital Elevation Model (DEM) is also downloaded and visualized with a terrain color scheme. Leafmap’s `layer_interact` method allows interactive adjustments." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "113", + "metadata": {}, + "outputs": [], + "source": [ + "m.layer_interact()" + ] + }, + { + "cell_type": "markdown", + "id": "114", + "metadata": {}, + "source": [ + "### Cloud Optimized GeoTIFF (COG)\n", + "\n", + "Cloud Optimized GeoTIFFs (COG) are large raster files stored on cloud platforms, allowing efficient streaming and loading. This example loads satellite imagery of Libya before and after an event, showing the change over time. Each image is loaded with `add_cog_layer`, and layers can be toggled for comparison. Using `fit_bounds`, the map centers on the COG layer to fit its boundaries." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "115", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(style=\"satellite\")\n", + "before = (\n", + " \"https://github.com/opengeos/datasets/releases/download/raster/Libya-2023-07-01.tif\"\n", + ")\n", + "after = (\n", + " \"https://github.com/opengeos/datasets/releases/download/raster/Libya-2023-09-13.tif\"\n", + ")\n", + "m.add_cog_layer(before, name=\"Before\", attribution=\"Maxar\")\n", + "m.add_cog_layer(after, name=\"After\", attribution=\"Maxar\", fit_bounds=True)\n", + "m.add_layer_control()\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "116", + "metadata": {}, + "outputs": [], + "source": [ + "m.layer_interact()" + ] + }, + { + "cell_type": "markdown", + "id": "117", + "metadata": {}, + "source": [ + "### STAC Layer\n", + "\n", + "The SpatioTemporal Asset Catalog (STAC) standard organizes large satellite data collections. With `add_stac_layer`, this example loads Canadian satellite data, displaying both a panchromatic and an RGB layer from the same source. This approach allows easy switching between views." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "118", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(style=\"streets\")\n", + "url = \"https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json\"\n", + "m.add_stac_layer(url, bands=[\"pan\"], name=\"Panchromatic\", vmin=0, vmax=150)\n", + "m.add_stac_layer(url, bands=[\"B4\", \"B3\", \"B2\"], name=\"RGB\", vmin=0, vmax=150)\n", + "m.add_layer_control()\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "119", + "metadata": {}, + "outputs": [], + "source": [ + "m.layer_interact()" + ] + }, + { + "cell_type": "markdown", + "id": "120", + "metadata": {}, + "source": [ + "For more control, the `collection` and `item` parameters let you specify specific assets, such as color infrared bands, for focused analysis." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "121", + "metadata": {}, + "outputs": [], + "source": [ + "collection = \"landsat-8-c2-l2\"\n", + "item = \"LC08_L2SP_047027_20201204_02_T1\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "122", + "metadata": {}, + "outputs": [], + "source": [ + "leafmap.stac_assets(collection=collection, item=item, titiler_endpoint=\"pc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "123", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(style=\"satellite\")\n", + "m.add_stac_layer(\n", + " collection=collection,\n", + " item=item,\n", + " assets=[\"SR_B5\", \"SR_B4\", \"SR_B3\"],\n", + " name=\"Color infrared\",\n", + ")\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "124", + "metadata": {}, + "source": [ + "## Interact with the Map\n", + "\n", + "Interactivity allows for a more tailored map experience.\n", + "\n", + "\n", + "### Display a Non-Interactive Map\n", + "\n", + "To create a static map, set `interactive=False`. This disables all user interactions, making it ideal for static presentations." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "125", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(\n", + " center=[-122.65, 45.52], zoom=9, interactive=False, style=\"liberty\", controls={}\n", + ")\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "126", + "metadata": {}, + "source": [ + "### Disable Scroll Zoom\n", + "\n", + "Use `scroll_zoom=False` to prevent map zooming with the scroll wheel, maintaining a fixed zoom level." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "127", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-122.65, 45.52], zoom=9, scroll_zoom=False, style=\"liberty\")\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "128", + "metadata": {}, + "source": [ + "### Fit Bounds\n", + "\n", + "The `fit_bounds` method focuses the map on a specified area. In this example, the map centers on Kenya. Additionally, a GeoJSON line is added to the map, and its bounds are automatically calculated with `geojson_bounds` for a custom zoom fit." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "129", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-74.5, 40], zoom=9, style=\"liberty\")\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "130", + "metadata": {}, + "source": [ + "Fit to Kenya." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "131", + "metadata": {}, + "outputs": [], + "source": [ + "bounds = [[32.958984, -5.353521], [43.50585, 5.615985]]\n", + "m.fit_bounds(bounds)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "132", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-77.0214, 38.897], zoom=12, style=\"liberty\")\n", + "\n", + "geojson = {\n", + " \"type\": \"FeatureCollection\",\n", + " \"features\": [\n", + " {\n", + " \"type\": \"Feature\",\n", + " \"geometry\": {\n", + " \"type\": \"LineString\",\n", + " \"properties\": {},\n", + " \"coordinates\": [\n", + " [-77.0366048812866, 38.89873175227713],\n", + " [-77.03364372253417, 38.89876515143842],\n", + " [-77.03364372253417, 38.89549195896866],\n", + " [-77.02982425689697, 38.89549195896866],\n", + " [-77.02400922775269, 38.89387200688839],\n", + " [-77.01519012451172, 38.891416957534204],\n", + " [-77.01521158218382, 38.892068305429156],\n", + " [-77.00813055038452, 38.892051604275686],\n", + " [-77.00832366943358, 38.89143365883688],\n", + " [-77.00818419456482, 38.89082405874451],\n", + " [-77.00815200805664, 38.88989712255097],\n", + " ],\n", + " },\n", + " }\n", + " ],\n", + "}\n", + "\n", + "m.add_source(\"LineString\", {\"type\": \"geojson\", \"data\": geojson})\n", + "layer = {\n", + " \"id\": \"LineString\",\n", + " \"type\": \"line\",\n", + " \"source\": \"LineString\",\n", + " \"layout\": {\"line-join\": \"round\", \"line-cap\": \"round\"},\n", + " \"paint\": {\"line-color\": \"#BF93E4\", \"line-width\": 5},\n", + "}\n", + "m.add_layer(layer)\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "133", + "metadata": {}, + "outputs": [], + "source": [ + "bounds = leafmap.geojson_bounds(geojson)\n", + "bounds" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "134", + "metadata": {}, + "outputs": [], + "source": [ + "m.fit_bounds(bounds)" + ] + }, + { + "cell_type": "markdown", + "id": "135", + "metadata": {}, + "source": [ + "### Restrict Map Panning to an Area\n", + "\n", + "To limit map panning to a specific area, define a bounding box. The map is then restricted within the bounds, ensuring users do not accidentally pan away from the area of interest." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "136", + "metadata": {}, + "outputs": [], + "source": [ + "bounds = [\n", + " [-74.04728500751165, 40.68392799015035],\n", + " [-73.91058699000139, 40.87764500765852],\n", + "]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "137", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-73.9978, 40.7209], zoom=13, max_bounds=bounds, style=\"liberty\")\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "138", + "metadata": {}, + "source": [ + "### Fly To\n", + "\n", + "The `fly_to` method smoothly navigates to specified coordinates. Parameters like speed and zoom provide control over the fly-to effect. This example flies from the initial map location to New York City." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "139", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-2.242467, 53.478122], zoom=9, style=\"liberty\")\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "140", + "metadata": {}, + "outputs": [], + "source": [ + "m.fly_to(lon=-73.983609, lat=40.754368, zoom=12)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "141", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-74.5, 40], zoom=9, style=\"liberty\")\n", + "m" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "142", + "metadata": {}, + "outputs": [], + "source": [ + "options = {\n", + " \"lon\": 74.5,\n", + " \"lat\": 40,\n", + " \"zoom\": 9,\n", + " \"bearing\": 0,\n", + " \"speed\": 0.2,\n", + " \"curve\": 1,\n", + " \"essential\": True,\n", + "}\n", + "\n", + "m.fly_to(**options)" + ] + }, + { + "cell_type": "markdown", + "id": "143", + "metadata": {}, + "source": [ + "### Jump to a Series of Locations\n", + "\n", + "Using `jump_to`, you can navigate between multiple locations. This example sets up a list of coordinates representing cities and automatically pans to each one in sequence. Adding a delay between transitions enhances the animation effect." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "144", + "metadata": {}, + "outputs": [], + "source": [ + "import time" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "145", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[100.507, 13.745], zoom=9, style=\"streets\")\n", + "\n", + "cities = {\n", + " \"type\": \"FeatureCollection\",\n", + " \"features\": [\n", + " {\n", + " \"type\": \"Feature\",\n", + " \"properties\": {},\n", + " \"geometry\": {\"type\": \"Point\", \"coordinates\": [100.507, 13.745]},\n", + " },\n", + " {\n", + " \"type\": \"Feature\",\n", + " \"properties\": {},\n", + " \"geometry\": {\"type\": \"Point\", \"coordinates\": [98.993, 18.793]},\n", + " },\n", + " {\n", + " \"type\": \"Feature\",\n", + " \"properties\": {},\n", + " \"geometry\": {\"type\": \"Point\", \"coordinates\": [99.838, 19.924]},\n", + " },\n", + " {\n", + " \"type\": \"Feature\",\n", + " \"properties\": {},\n", + " \"geometry\": {\"type\": \"Point\", \"coordinates\": [102.812, 17.408]},\n", + " },\n", + " {\n", + " \"type\": \"Feature\",\n", + " \"properties\": {},\n", + " \"geometry\": {\"type\": \"Point\", \"coordinates\": [100.458, 7.001]},\n", + " },\n", + " {\n", + " \"type\": \"Feature\",\n", + " \"properties\": {},\n", + " \"geometry\": {\"type\": \"Point\", \"coordinates\": [100.905, 12.935]},\n", + " },\n", + " ],\n", + "}\n", "m" ] }, { "cell_type": "code", "execution_count": null, - "id": "63", + "id": "146", "metadata": {}, "outputs": [], "source": [ - "m.layer_interact()" + "for index, city in enumerate(cities[\"features\"]):\n", + " time.sleep(2)\n", + " coords = city[\"geometry\"][\"coordinates\"]\n", + " m.jump_to({\"center\": coords})" ] }, { "cell_type": "markdown", - "id": "64", + "id": "147", "metadata": {}, "source": [ - "### Marker cluster\n", + "### Get Coordinates of the Mouse Pointer\n", "\n", - "Create a marker cluster layer." + "With widgets, you can display the current mouse pointer coordinates as it moves across the map. This is useful for precision mapping tasks where knowing exact coordinates is essential." ] }, { "cell_type": "code", "execution_count": null, - "id": "65", + "id": "148", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-103.59179, 40.66995], zoom=3, style=\"streets\")\n", - "data = \"https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson\"\n", - "source_args = {\n", - " \"cluster\": True,\n", - " \"cluster_radius\": 50,\n", - " \"cluster_min_points\": 2,\n", - " \"cluster_max_zoom\": 14,\n", - " \"cluster_properties\": {\n", - " \"maxMag\": [\"max\", [\"get\", \"mag\"]],\n", - " \"minMag\": [\"min\", [\"get\", \"mag\"]],\n", - " },\n", - "}\n", - "\n", - "m.add_geojson(\n", - " data,\n", - " layer_type=\"circle\",\n", - " name=\"earthquake-circles\",\n", - " filter=[\"!\", [\"has\", \"point_count\"]],\n", - " paint={\"circle-color\": \"darkblue\"},\n", - " source_args=source_args,\n", - ")\n", - "\n", - "m.add_geojson(\n", - " data,\n", - " layer_type=\"circle\",\n", - " name=\"earthquake-clusters\",\n", - " filter=[\"has\", \"point_count\"],\n", - " paint={\n", - " \"circle-color\": [\n", - " \"step\",\n", - " [\"get\", \"point_count\"],\n", - " \"#51bbd6\",\n", - " 100,\n", - " \"#f1f075\",\n", - " 750,\n", - " \"#f28cb1\",\n", - " ],\n", - " \"circle-radius\": [\"step\", [\"get\", \"point_count\"], 20, 100, 30, 750, 40],\n", - " },\n", - " source_args=source_args,\n", - ")\n", - "\n", - "m.add_geojson(\n", - " data,\n", - " layer_type=\"symbol\",\n", - " name=\"earthquake-labels\",\n", - " filter=[\"has\", \"point_count\"],\n", - " layout={\n", - " \"text-field\": [\"get\", \"point_count_abbreviated\"],\n", - " \"text-size\": 12,\n", - " },\n", - " source_args=source_args,\n", - ")\n", - "m" - ] - }, - { - "cell_type": "markdown", - "id": "66", - "metadata": {}, - "source": [ - "### Local vector data\n", - "\n", - "You can load local vector data interactively using the `open_geojson` method." + "import ipywidgets as widgets" ] }, { "cell_type": "code", "execution_count": null, - "id": "67", + "id": "149", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-100, 40], zoom=3)\n", + "m = leafmap.Map(center=[-74.5, 40], zoom=9, style=\"streets\")\n", "m" ] }, { "cell_type": "code", "execution_count": null, - "id": "68", + "id": "150", "metadata": {}, "outputs": [], "source": [ - "url = \"https://github.com/opengeos/datasets/releases/download/us/us_states.geojson\"\n", - "filepath = \"data/us_states.geojson\"\n", - "leafmap.download_file(url, filepath, quiet=True)" + "m.clicked" ] }, { "cell_type": "code", "execution_count": null, - "id": "69", + "id": "151", "metadata": {}, "outputs": [], "source": [ - "m.open_geojson()" + "output = widgets.Output()\n", + "\n", + "\n", + "def log_lng_lat(lng_lat):\n", + " with output:\n", + " output.clear_output()\n", + " print(lng_lat.new)\n", + "\n", + "\n", + "m.observe(log_lng_lat, names=\"clicked\")\n", + "output" ] }, { "cell_type": "markdown", - "id": "70", + "id": "152", "metadata": {}, "source": [ - "### Change building color" + "## Customizing Layer Styles\n", + "\n", + "Customizing layer styles enables personalized map designs.\n", + "\n", + "### Change Layer Color\n", + "\n", + "Use `style_layer_interact` to interactively change the color of map layers, such as water bodies. This method provides an interactive palette for immediate style changes." ] }, { "cell_type": "code", "execution_count": null, - "id": "71", + "id": "153", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-90.73414, 14.55524], zoom=13, style=\"basic\")\n", - "m.set_paint_property(\n", - " \"building\",\n", - " \"fill-color\",\n", - " [\"interpolate\", [\"exponential\", 0.5], [\"zoom\"], 15, \"#e2714b\", 22, \"#eee695\"],\n", - ")\n", - "m.set_paint_property(\n", - " \"building\",\n", - " \"fill-opacity\",\n", - " [\"interpolate\", [\"exponential\", 0.5], [\"zoom\"], 15, 0, 22, 1],\n", - ")\n", + "m = leafmap.Map(center=[12.338, 45.4385], zoom=17, style=\"streets\")\n", "m" ] }, { "cell_type": "code", "execution_count": null, - "id": "72", + "id": "154", "metadata": {}, "outputs": [], "source": [ - "m.add_call(\"zoomTo\", 19, {\"duration\": 9000})" + "m.style_layer_interact(id=\"water\")" ] }, { "cell_type": "markdown", - "id": "73", + "id": "155", "metadata": {}, "source": [ - "### Live feature update\n", + "### Change Case of Labels\n", "\n", - "#### Animate a point along a route" + "This example displays labels in upper or lower case based on their properties. The layout options let you customize font, size, and alignment. For example, facility names are displayed in uppercase, and comments are displayed in lowercase for contrast." ] }, { "cell_type": "code", "execution_count": null, - "id": "74", + "id": "156", "metadata": {}, "outputs": [], "source": [ - "import time" + "m = leafmap.Map(center=[-116.231, 43.604], zoom=11, style=\"streets\")\n", + "geojson = {\n", + " \"type\": \"geojson\",\n", + " \"data\": \"https://maplibre.org/maplibre-gl-js/docs/assets/boise.geojson\",\n", + "}\n", + "m.add_source(\"off-leash-areas\", geojson)\n", + "layer = {\n", + " \"id\": \"off-leash-areas\",\n", + " \"type\": \"symbol\",\n", + " \"source\": \"off-leash-areas\",\n", + " \"layout\": {\n", + " \"icon-image\": \"dog-park-11\",\n", + " \"text-field\": [\n", + " \"format\",\n", + " [\"upcase\", [\"get\", \"FacilityName\"]],\n", + " {\"font-scale\": 0.8},\n", + " \"\\n\",\n", + " {},\n", + " [\"downcase\", [\"get\", \"Comments\"]],\n", + " {\"font-scale\": 0.6},\n", + " ],\n", + " \"text-font\": [\"Open Sans Semibold\", \"Arial Unicode MS Bold\"],\n", + " \"text-offset\": [0, 0.6],\n", + " \"text-anchor\": \"top\",\n", + " },\n", + "}\n", + "m.add_layer(layer)\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "157", + "metadata": {}, + "source": [ + "### Variable Label Placement\n", + "\n", + "Labels can be automatically positioned around features with `text-variable-anchor`. This example defines multiple anchor points for labels to avoid overlap and ensure clear visibility. The radial offset and auto-justification properties create a professional, clutter-free appearance around points of interest." ] }, { "cell_type": "code", "execution_count": null, - "id": "75", + "id": "158", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"streets\")\n", - "url = \"https://github.com/opengeos/datasets/releases/download/us/arc_with_bearings.geojson\"\n", - "geojson = requests.get(url).json()\n", - "bearings = geojson[\"features\"][0][\"properties\"][\"bearings\"]\n", - "coordinates = geojson[\"features\"][0][\"geometry\"][\"coordinates\"][:-1]\n", - "m.add_geojson(geojson, name=\"route\")\n", - "\n", - "origin = [-122.414, 37.776]\n", - "destination = [-77.032, 38.913]\n", + "m = leafmap.Map(center=[-77.04, 38.907], zoom=11, style=\"streets\")\n", "\n", - "point = {\n", + "places = {\n", " \"type\": \"FeatureCollection\",\n", " \"features\": [\n", " {\n", " \"type\": \"Feature\",\n", - " \"properties\": {},\n", - " \"geometry\": {\"type\": \"Point\", \"coordinates\": origin},\n", - " }\n", + " \"properties\": {\"description\": \"Ford's Theater\", \"icon\": \"theatre\"},\n", + " \"geometry\": {\"type\": \"Point\", \"coordinates\": [-77.038659, 38.931567]},\n", + " },\n", + " {\n", + " \"type\": \"Feature\",\n", + " \"properties\": {\"description\": \"The Gaslight\", \"icon\": \"theatre\"},\n", + " \"geometry\": {\"type\": \"Point\", \"coordinates\": [-77.003168, 38.894651]},\n", + " },\n", + " {\n", + " \"type\": \"Feature\",\n", + " \"properties\": {\"description\": \"Horrible Harry's\", \"icon\": \"bar\"},\n", + " \"geometry\": {\"type\": \"Point\", \"coordinates\": [-77.090372, 38.881189]},\n", + " },\n", + " {\n", + " \"type\": \"Feature\",\n", + " \"properties\": {\"description\": \"Bike Party\", \"icon\": \"bicycle\"},\n", + " \"geometry\": {\"type\": \"Point\", \"coordinates\": [-77.052477, 38.943951]},\n", + " },\n", + " {\n", + " \"type\": \"Feature\",\n", + " \"properties\": {\"description\": \"Rockabilly Rockstars\", \"icon\": \"music\"},\n", + " \"geometry\": {\"type\": \"Point\", \"coordinates\": [-77.031706, 38.914581]},\n", + " },\n", + " {\n", + " \"type\": \"Feature\",\n", + " \"properties\": {\"description\": \"District Drum Tribe\", \"icon\": \"music\"},\n", + " \"geometry\": {\"type\": \"Point\", \"coordinates\": [-77.020945, 38.878241]},\n", + " },\n", + " {\n", + " \"type\": \"Feature\",\n", + " \"properties\": {\"description\": \"Motown Memories\", \"icon\": \"music\"},\n", + " \"geometry\": {\"type\": \"Point\", \"coordinates\": [-77.007481, 38.876516]},\n", + " },\n", " ],\n", "}\n", - "source = {\"type\": \"geojson\", \"data\": point}\n", - "m.add_source(\"point\", source)\n", + "source = {\"type\": \"geojson\", \"data\": places}\n", + "m.add_source(\"places\", source)\n", + "\n", "layer = {\n", - " \"id\": \"point\",\n", - " \"source\": \"point\",\n", + " \"id\": \"poi-labels\",\n", " \"type\": \"symbol\",\n", + " \"source\": \"places\",\n", " \"layout\": {\n", - " \"icon-image\": \"airport_15\",\n", - " \"icon-rotate\": [\"get\", \"bearing\"],\n", - " \"icon-rotation-alignment\": \"map\",\n", - " \"icon-overlap\": \"always\",\n", - " \"icon-ignore-placement\": True,\n", + " \"text-field\": [\"get\", \"description\"],\n", + " \"text-variable-anchor\": [\"top\", \"bottom\", \"left\", \"right\"],\n", + " \"text-radial-offset\": 0.5,\n", + " \"text-justify\": \"auto\",\n", + " \"icon-image\": [\"concat\", [\"get\", \"icon\"], \"_15\"],\n", " },\n", "}\n", "m.add_layer(layer)\n", @@ -1187,348 +2611,515 @@ { "cell_type": "code", "execution_count": null, - "id": "76", + "id": "159", "metadata": {}, "outputs": [], "source": [ - "for index, coordinate in enumerate(coordinates):\n", - " point[\"features\"][0][\"geometry\"][\"coordinates\"] = coordinate\n", - " point[\"features\"][0][\"properties\"][\"bearing\"] = bearings[index]\n", - " m.set_data(\"point\", point)\n", - " time.sleep(0.05)" + "m.rotate_to(bearing=180, options={\"duration\": 10000})" ] }, { "cell_type": "markdown", - "id": "77", + "id": "160", + "metadata": {}, + "source": [ + "## Adding Custom Components\n", + "\n", + "Enhance your maps by adding custom components such as images, videos, text, color bars, and legends.\n", + "\n", + "### Add Image\n", + "\n", + "You can add an image as an overlay or as an icon for a specific layer. For instance:\n", + "- Overlaying an image directly on the map at the \"bottom-right\" corner.\n", + "- Adding an icon image to a feature. In the example, a \"cat\" image is loaded, and a marker is added at coordinates `[0, 0]` with a label \"I love kitty!\" above the icon." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "161", "metadata": {}, + "outputs": [], "source": [ - "#### Update a feature in realtime" + "m = leafmap.Map(center=[0.349419, -1.80921], zoom=3, style=\"streets\")\n", + "image = \"https://upload.wikimedia.org/wikipedia/commons/7/7c/201408_cat.png\"\n", + "source = {\n", + " \"type\": \"geojson\",\n", + " \"data\": {\n", + " \"type\": \"FeatureCollection\",\n", + " \"features\": [\n", + " {\"type\": \"Feature\", \"geometry\": {\"type\": \"Point\", \"coordinates\": [0, 0]}}\n", + " ],\n", + " },\n", + "}\n", + "\n", + "layer = {\n", + " \"id\": \"points\",\n", + " \"type\": \"symbol\",\n", + " \"source\": \"point\",\n", + " \"layout\": {\n", + " \"icon-image\": \"cat\",\n", + " \"icon-size\": 0.25,\n", + " \"text-field\": \"I love kitty!\",\n", + " \"text-font\": [\"Open Sans Regular\"],\n", + " \"text-offset\": [0, 3],\n", + " \"text-anchor\": \"top\",\n", + " },\n", + "}\n", + "m.add_image(\"cat\", image)\n", + "m.add_source(\"point\", source)\n", + "m.add_layer(layer)\n", + "m" ] }, { "cell_type": "code", "execution_count": null, - "id": "78", + "id": "162", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-122.019807, 45.632433], zoom=14, pitch=60, style=\"3d-terrain\")\n", + "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", + "image = \"https://i.imgur.com/LmTETPX.png\"\n", + "m.add_image(image=image, position=\"bottom-right\")\n", "m" ] }, { "cell_type": "code", "execution_count": null, - "id": "79", + "id": "163", "metadata": {}, "outputs": [], "source": [ - "import geopandas as gpd" + "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", + "content = ''\n", + "m.add_html(content, bg_color=\"transparent\", position=\"bottom-right\")\n", + "m" ] }, { - "cell_type": "code", - "execution_count": null, - "id": "80", + "cell_type": "markdown", + "id": "164", "metadata": {}, - "outputs": [], "source": [ - "url = \"https://maplibre.org/maplibre-gl-js/docs/assets/hike.geojson\"\n", - "gdf = gpd.read_file(url)\n", - "coordinates = list(gdf.geometry[0].coords)\n", - "print(coordinates[:5])" + "To customize icons, you can also generate icon data with `numpy`, creating unique color gradients and using it as a map icon." ] }, { "cell_type": "code", "execution_count": null, - "id": "81", + "id": "165", "metadata": {}, "outputs": [], "source": [ + "import numpy as np\n", + "\n", + "\n", + "# Generate the icon data\n", + "width = 64 # The image will be 64 pixels square\n", + "height = 64\n", + "bytes_per_pixel = 4 # Each pixel is represented by 4 bytes: red, green, blue, and alpha\n", + "data = np.zeros((width, width, bytes_per_pixel), dtype=np.uint8)\n", + "\n", + "for x in range(width):\n", + " for y in range(width):\n", + " data[y, x, 0] = int((y / width) * 255) # red\n", + " data[y, x, 1] = int((x / width) * 255) # green\n", + " data[y, x, 2] = 128 # blue\n", + " data[y, x, 3] = 255 # alpha\n", + "\n", + "# Flatten the data array\n", + "flat_data = data.flatten()\n", + "\n", + "# Create the image dictionary\n", + "image_dict = {\n", + " \"width\": width,\n", + " \"height\": height,\n", + " \"data\": flat_data.tolist(),\n", + "}\n", + "\n", + "m = leafmap.Map(center=[0, 0], zoom=1, style=\"liberty\")\n", + "m.add_image(\"gradient\", image_dict)\n", "source = {\n", " \"type\": \"geojson\",\n", " \"data\": {\n", - " \"type\": \"Feature\",\n", - " \"geometry\": {\"type\": \"LineString\", \"coordinates\": [coordinates[0]]},\n", + " \"type\": \"FeatureCollection\",\n", + " \"features\": [\n", + " {\"type\": \"Feature\", \"geometry\": {\"type\": \"Point\", \"coordinates\": [0, 0]}}\n", + " ],\n", " },\n", "}\n", - "m.add_source(\"trace\", source)\n", + "\n", "layer = {\n", - " \"id\": \"trace\",\n", - " \"type\": \"line\",\n", - " \"source\": \"trace\",\n", - " \"paint\": {\"line-color\": \"yellow\", \"line-opacity\": 0.75, \"line-width\": 5},\n", + " \"id\": \"points\",\n", + " \"type\": \"symbol\",\n", + " \"source\": \"point\",\n", + " \"layout\": {\"icon-image\": \"gradient\"},\n", "}\n", + "\n", + "m.add_source(\"point\", source)\n", "m.add_layer(layer)\n", - "m.jump_to({\"center\": coordinates[0], \"zoom\": 14})\n", - "m.set_pitch(30)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "82", - "metadata": {}, - "outputs": [], - "source": [ - "for coord in coordinates:\n", - " time.sleep(0.005)\n", - " source[\"data\"][\"geometry\"][\"coordinates\"].append(coord)\n", - " m.set_data(\"trace\", source[\"data\"])\n", - " m.pan_to(coord)" + "m" ] }, { "cell_type": "markdown", - "id": "83", + "id": "166", "metadata": {}, "source": [ - "## Visualize raster data\n", + "### Add Text\n", "\n", - "### Local raster data\n", - "\n", - "You can load local raster data using the `add_raster` method." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "84", - "metadata": {}, - "outputs": [], - "source": [ - "url = \"https://github.com/opengeos/datasets/releases/download/raster/landsat.tif\"\n", - "filepath = \"landsat.tif\"\n", - "leafmap.download_file(url, filepath)" + "Add text annotations to the map, specifying parameters like font size and background color. For example:\n", + "- Text \"Hello World\" in the bottom-right corner with a transparent background.\n", + "- \"Awesome Text!\" in the top-left corner with a slightly opaque white background, making it stand out." ] }, { "cell_type": "code", "execution_count": null, - "id": "85", + "id": "167", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(style=\"streets\")\n", - "m.add_raster(filepath, indexes=[3, 2, 1], vmin=0, vmax=100, name=\"Landsat-321\")\n", - "m.add_raster(filepath, indexes=[4, 3, 2], vmin=0, vmax=100, name=\"Landsat-432\")\n", + "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"liberty\")\n", + "text = \"Hello World\"\n", + "m.add_text(text, fontsize=20, position=\"bottom-right\")\n", + "text2 = \"Awesome Text!\"\n", + "m.add_text(text2, fontsize=25, bg_color=\"rgba(255, 255, 255, 0.8)\", position=\"top-left\")\n", "m" ] }, { - "cell_type": "code", - "execution_count": null, - "id": "86", + "cell_type": "markdown", + "id": "168", "metadata": {}, - "outputs": [], "source": [ - "m.layer_interact()" + "### Add GIF\n", + "\n", + "GIFs can be added as animated overlays to bring your map to life. Example: add a sloth GIF in the bottom-right and a second GIF in the bottom-left corner, with a text label indicating “I love sloth!” for added character." ] }, { "cell_type": "code", "execution_count": null, - "id": "87", + "id": "169", "metadata": {}, "outputs": [], "source": [ - "url = \"https://github.com/opengeos/datasets/releases/download/raster/srtm90.tif\"\n", - "filepath = \"srtm90.tif\"\n", - "leafmap.download_file(url, filepath)" + "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", + "image = \"https://i.imgur.com/KeiAsTv.gif\"\n", + "m.add_image(image=image, width=250, height=250, position=\"bottom-right\")\n", + "text = \"I love sloth!🦥\"\n", + "m.add_text(text, fontsize=35, padding=\"20px\")\n", + "image2 = \"https://i.imgur.com/kZC2tpr.gif\"\n", + "m.add_image(image=image2, bg_color=\"transparent\", position=\"bottom-left\")\n", + "m" ] }, { - "cell_type": "code", - "execution_count": null, - "id": "88", + "cell_type": "markdown", + "id": "170", "metadata": {}, - "outputs": [], "source": [ - "m = leafmap.Map(style=\"satellite\")\n", - "m.add_raster(filepath, colormap=\"terrain\", name=\"DEM\")\n", - "m" + "### Add HTML\n", + "\n", + "Embed custom HTML content to display various HTML elements, such as emojis or stylized text. You can also adjust the font size and background transparency for better integration into the map design." ] }, { "cell_type": "code", "execution_count": null, - "id": "89", + "id": "171", "metadata": {}, "outputs": [], "source": [ - "m.layer_interact()" + "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", + "html = \"\"\"\n", + "\n", + "\n", + "\n", + "\n", + "🚀\n", + "

I will display 🚁

\n", + "

I will display 🚂

\n", + "\n", + "\n", + "\n", + "\"\"\"\n", + "m.add_html(html, bg_color=\"transparent\")\n", + "m" ] }, { "cell_type": "markdown", - "id": "90", + "id": "172", "metadata": {}, "source": [ - "### Cloud Optimized GeoTIFF (COG)\n", + "### Add Colorbar\n", "\n", - "You can load Cloud Optimized GeoTIFF (COG) data using the `add_cog_layer` method." + "Adding a color bar enhances data interpretation. In the example:\n", + "1. A Digital Elevation Model (DEM) is displayed with a color ramp from 0 to 1500 meters.\n", + "2. `add_colorbar` method is used to create a color bar with labels, adjusting its position, opacity, and orientation for optimal readability." ] }, { "cell_type": "code", "execution_count": null, - "id": "91", + "id": "173", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(style=\"satellite\")\n", - "before = (\n", - " \"https://github.com/opengeos/datasets/releases/download/raster/Libya-2023-07-01.tif\"\n", + "m = leafmap.Map(style=\"topo\")\n", + "dem = \"https://github.com/opengeos/datasets/releases/download/raster/dem.tif\"\n", + "m.add_cog_layer(\n", + " dem,\n", + " name=\"DEM\",\n", + " colormap_name=\"terrain\",\n", + " rescale=\"0, 1500\",\n", + " fit_bounds=True,\n", + " nodata=np.nan,\n", ")\n", - "after = (\n", - " \"https://github.com/opengeos/datasets/releases/download/raster/Libya-2023-09-13.tif\"\n", + "m.add_colorbar(\n", + " cmap=\"terrain\", vmin=0, vmax=1500, label=\"Elevation (m)\", position=\"bottom-right\"\n", ")\n", - "m.add_cog_layer(before, name=\"Before\", attribution=\"Maxar\")\n", - "m.add_cog_layer(after, name=\"After\", attribution=\"Maxar\", fit_bounds=True)\n", + "m.add_layer_control()\n", "m" ] }, { "cell_type": "code", "execution_count": null, - "id": "92", + "id": "174", "metadata": {}, "outputs": [], "source": [ - "m.layer_interact()" - ] - }, - { - "cell_type": "markdown", - "id": "93", - "metadata": {}, - "source": [ - "### STAC layer\n", - "\n", - "You can load SpatioTemporal Asset Catalog (STAC) data using the `add_stac_layer` method." + "m = leafmap.Map(style=\"topo\")\n", + "m.add_cog_layer(\n", + " dem,\n", + " name=\"DEM\",\n", + " colormap_name=\"terrain\",\n", + " rescale=\"0, 1500\",\n", + " nodata=np.nan,\n", + " fit_bounds=True,\n", + ")\n", + "m.add_colorbar(\n", + " cmap=\"terrain\",\n", + " vmin=0,\n", + " vmax=1500,\n", + " label=\"Elevation (m)\",\n", + " position=\"bottom-right\",\n", + " transparent=True,\n", + ")\n", + "m" ] }, { "cell_type": "code", "execution_count": null, - "id": "94", + "id": "175", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map()\n", - "url = \"https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json\"\n", - "m.add_stac_layer(url, bands=[\"B4\", \"B3\", \"B2\"], name=\"SPOT\", vmin=0, vmax=150, nodata=0)\n", + "m = leafmap.Map(style=\"topo\")\n", + "m.add_cog_layer(\n", + " dem,\n", + " name=\"DEM\",\n", + " colormap_name=\"terrain\",\n", + " rescale=\"0, 1500\",\n", + " nodata=np.nan,\n", + " fit_bounds=True,\n", + ")\n", + "m.add_colorbar(\n", + " cmap=\"terrain\",\n", + " vmin=0,\n", + " vmax=1500,\n", + " label=\"Elevation (m)\",\n", + " position=\"bottom-right\",\n", + " width=0.2,\n", + " height=3,\n", + " orientation=\"vertical\",\n", + ")\n", "m" ] }, { "cell_type": "markdown", - "id": "95", + "id": "176", "metadata": {}, "source": [ - "## Customize layer styles" + "### Add Legend\n", + "\n", + "Custom legends help users understand data classifications. Two methods are shown:\n", + "1. Using built-in legends, such as for NLCD (National Land Cover Database) or wetland types.\n", + "2. Custom legends are built with a dictionary of land cover types and colors. This legend provides descriptive color-coding for various land cover types, with configurable background opacity to blend with the map." ] }, { - "cell_type": "markdown", - "id": "96", + "cell_type": "code", + "execution_count": null, + "id": "177", "metadata": {}, + "outputs": [], "source": [ - "### Change layer color" + "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", + "m.add_basemap(\"Esri.WorldImagery\")\n", + "url = \"https://www.mrlc.gov/geoserver/mrlc_display/NLCD_2021_Land_Cover_L48/wms\"\n", + "layers = \"NLCD_2021_Land_Cover_L48\"\n", + "m.add_wms_layer(url, layers=layers, name=\"NLCD 2021\")\n", + "m.add_legend(\n", + " title=\"NLCD Land Cover Type\",\n", + " builtin_legend=\"NLCD\",\n", + " bg_color=\"rgba(255, 255, 255, 0.5)\",\n", + " position=\"bottom-left\",\n", + ")\n", + "m" ] }, { "cell_type": "code", "execution_count": null, - "id": "97", + "id": "178", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[12.338, 45.4385], zoom=17, style=\"streets\")\n", + "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", + "m.add_basemap(\"Esri.WorldImagery\")\n", + "url = \"https://fwspublicservices.wim.usgs.gov/wetlandsmapservice/services/Wetlands/MapServer/WMSServer\"\n", + "m.add_wms_layer(url, layers=\"1\", name=\"NWI\", opacity=0.6)\n", + "m.add_layer_control()\n", + "m.add_legend(builtin_legend=\"NWI\", title=\"Wetland Type\")\n", "m" ] }, { "cell_type": "code", "execution_count": null, - "id": "98", + "id": "179", "metadata": {}, "outputs": [], "source": [ - "m.style_layer_interact(id=\"water\")" + "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", + "m.add_basemap(\"Esri.WorldImagery\")\n", + "url = \"https://www.mrlc.gov/geoserver/mrlc_display/NLCD_2021_Land_Cover_L48/wms\"\n", + "layers = \"NLCD_2021_Land_Cover_L48\"\n", + "m.add_wms_layer(url, layers=layers, name=\"NLCD 2021\")\n", + "\n", + "legend_dict = {\n", + " \"11 Open Water\": \"466b9f\",\n", + " \"12 Perennial Ice/Snow\": \"d1def8\",\n", + " \"21 Developed, Open Space\": \"dec5c5\",\n", + " \"22 Developed, Low Intensity\": \"d99282\",\n", + " \"23 Developed, Medium Intensity\": \"eb0000\",\n", + " \"24 Developed High Intensity\": \"ab0000\",\n", + " \"31 Barren Land (Rock/Sand/Clay)\": \"b3ac9f\",\n", + " \"41 Deciduous Forest\": \"68ab5f\",\n", + " \"42 Evergreen Forest\": \"1c5f2c\",\n", + " \"43 Mixed Forest\": \"b5c58f\",\n", + " \"51 Dwarf Scrub\": \"af963c\",\n", + " \"52 Shrub/Scrub\": \"ccb879\",\n", + " \"71 Grassland/Herbaceous\": \"dfdfc2\",\n", + " \"72 Sedge/Herbaceous\": \"d1d182\",\n", + " \"73 Lichens\": \"a3cc51\",\n", + " \"74 Moss\": \"82ba9e\",\n", + " \"81 Pasture/Hay\": \"dcd939\",\n", + " \"82 Cultivated Crops\": \"ab6c28\",\n", + " \"90 Woody Wetlands\": \"b8d9eb\",\n", + " \"95 Emergent Herbaceous Wetlands\": \"6c9fb8\",\n", + "}\n", + "m.add_legend(\n", + " title=\"NLCD Land Cover Type\",\n", + " legend_dict=legend_dict,\n", + " bg_color=\"rgba(255, 255, 255, 0.5)\",\n", + " position=\"bottom-left\",\n", + ")\n", + "m" ] }, { "cell_type": "markdown", - "id": "99", + "id": "180", "metadata": {}, "source": [ - "### Change case of labels" + "### Add Video\n", + "\n", + "Videos can be added with geographic context by specifying corner coordinates. Videos must be listed in multiple formats to ensure compatibility across browsers. The coordinates array should define the video’s location on the map in the order: top-left, top-right, bottom-right, and bottom-left. This is demonstrated by adding drone footage to a satellite map view, enhancing the user experience with real-world visuals.\n", + "\n", + "\n", + "The `urls` value is an array. For each URL in the array, a video element source will be created. To support the video across browsers, supply URLs in multiple formats.\n", + "The `coordinates` array contains [longitude, latitude] pairs for the video corners listed in clockwise order: top left, top right, bottom right, bottom left." ] }, { "cell_type": "code", "execution_count": null, - "id": "100", + "id": "181", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-116.231, 43.604], zoom=11, style=\"streets\")\n", - "geojson = {\n", - " \"type\": \"geojson\",\n", - " \"data\": \"https://maplibre.org/maplibre-gl-js/docs/assets/boise.geojson\",\n", - "}\n", - "m.add_source(\"off-leash-areas\", geojson)\n", - "layer = {\n", - " \"id\": \"off-leash-areas\",\n", - " \"type\": \"symbol\",\n", - " \"source\": \"off-leash-areas\",\n", - " \"layout\": {\n", - " \"icon-image\": \"dog-park-11\",\n", - " \"text-field\": [\n", - " \"format\",\n", - " [\"upcase\", [\"get\", \"FacilityName\"]],\n", - " {\"font-scale\": 0.8},\n", - " \"\\n\",\n", - " {},\n", - " [\"downcase\", [\"get\", \"Comments\"]],\n", - " {\"font-scale\": 0.6},\n", - " ],\n", - " \"text-font\": [\"Open Sans Semibold\", \"Arial Unicode MS Bold\"],\n", - " \"text-offset\": [0, 0.6],\n", - " \"text-anchor\": \"top\",\n", - " },\n", - "}\n", - "m.add_layer(layer)\n", + "m = leafmap.Map(\n", + " center=[-122.514426, 37.562984], zoom=17, bearing=-96, style=\"satellite\"\n", + ")\n", + "urls = [\n", + " \"https://static-assets.mapbox.com/mapbox-gl-js/drone.mp4\",\n", + " \"https://static-assets.mapbox.com/mapbox-gl-js/drone.webm\",\n", + "]\n", + "coordinates = [\n", + " [-122.51596391201019, 37.56238816766053],\n", + " [-122.51467645168304, 37.56410183312965],\n", + " [-122.51309394836426, 37.563391708549425],\n", + " [-122.51423120498657, 37.56161849366671],\n", + "]\n", + "m.add_video(urls, coordinates)\n", + "m.add_layer_control()\n", "m" ] }, { "cell_type": "code", "execution_count": null, - "id": "101", + "id": "182", "metadata": {}, "outputs": [], - "source": [] + "source": [ + "m = leafmap.Map(center=[-115, 25], zoom=4, style=\"satellite\")\n", + "urls = [\n", + " \"https://data.opengeos.org/patricia_nasa.mp4\",\n", + " \"https://data.opengeos.org/patricia_nasa.webm\",\n", + "]\n", + "coordinates = [\n", + " [-130, 32],\n", + " [-100, 32],\n", + " [-100, 13],\n", + " [-130, 13],\n", + "]\n", + "m.add_video(urls, coordinates)\n", + "m.add_layer_control()\n", + "m" + ] }, { "cell_type": "markdown", - "id": "102", + "id": "183", "metadata": {}, "source": [ "## PMTiles\n", "\n", - "Leafmap supports the [PMTiles](https://protomaps.com/docs/pmtiles/) format for fast and efficient rendering of vector tiles.\n", + "Leafmap supports the [PMTiles](https://protomaps.com/docs/pmtiles/) format, enabling efficient storage and fast rendering of vector tiles directly in the browser.\n", + "\n", + "### Protomaps Sample Data\n", "\n", - "### Protomaps sample data" + "Load Protomaps data in PMTiles format for fast, high-resolution vector map data rendering. Use `pmtiles_metadata()` to fetch details like layer names and map bounds, then style and add these tiles to your map. For instance, the example shows two layers: `buildings` styled in \"steelblue\" and `roads` styled in \"black\"." ] }, { "cell_type": "code", "execution_count": null, - "id": "103", + "id": "184", "metadata": {}, "outputs": [], "source": [ @@ -1541,7 +3132,7 @@ { "cell_type": "code", "execution_count": null, - "id": "104", + "id": "185", "metadata": {}, "outputs": [], "source": [ @@ -1589,7 +3180,7 @@ { "cell_type": "code", "execution_count": null, - "id": "105", + "id": "186", "metadata": {}, "outputs": [], "source": [ @@ -1598,20 +3189,12 @@ }, { "cell_type": "markdown", - "id": "106", + "id": "187", "metadata": {}, "source": [ - "### Overture data\n", + "### Source Cooperative Data\n", "\n", - "You can also visualize Overture data. Inspired by [overture-maps](https://github.com/tebben/overture-maps)." - ] - }, - { - "cell_type": "markdown", - "id": "107", - "metadata": {}, - "source": [ - "### Source Cooperative\n", + "Visualize the Google-Microsoft Open Buildings dataset, managed by VIDA, in PMTiles format. Fetch metadata to identify available layers, apply custom styles to the building footprints, and render them with semi-transparent colors for a clear visualization.\n", "\n", "Let's visualize the [Google-Microsoft Open Buildings - combined by VIDA](https://beta.source.coop/repositories/vida/google-microsoft-open-buildings/description)." ] @@ -1619,7 +3202,7 @@ { "cell_type": "code", "execution_count": null, - "id": "108", + "id": "188", "metadata": {}, "outputs": [], "source": [ @@ -1632,11 +3215,11 @@ { "cell_type": "code", "execution_count": null, - "id": "109", + "id": "189", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[0, 20], zoom=2, height=\"800px\")\n", + "m = leafmap.Map(center=[0, 20], zoom=2)\n", "m.add_basemap(\"Google Hybrid\", visible=False)\n", "\n", "style = {\n", @@ -1674,7 +3257,7 @@ { "cell_type": "code", "execution_count": null, - "id": "110", + "id": "190", "metadata": {}, "outputs": [], "source": [ @@ -1683,18 +3266,18 @@ }, { "cell_type": "markdown", - "id": "111", + "id": "191", "metadata": {}, "source": [ "### 3D PMTiles\n", "\n", - "Visualize the global building data in 3D." + "Render global building data in 3D for a realistic, textured experience. Set building colors and extrusion heights to create visually compelling cityscapes. For example, apply color gradients and height scaling based on building attributes to differentiate buildings by their heights." ] }, { "cell_type": "code", "execution_count": null, - "id": "112", + "id": "192", "metadata": {}, "outputs": [], "source": [ @@ -1707,7 +3290,7 @@ { "cell_type": "code", "execution_count": null, - "id": "113", + "id": "193", "metadata": {}, "outputs": [], "source": [ @@ -1762,16 +3345,18 @@ }, { "cell_type": "markdown", - "id": "114", + "id": "194", "metadata": {}, "source": [ - "### 3D buildings" + "### 3D Buildings\n", + "\n", + "For a simplified setup, the `add_overture_3d_buildings` function quickly adds 3D building data from Overture’s latest release to a basemap, creating depth and spatial realism on the map." ] }, { "cell_type": "code", "execution_count": null, - "id": "115", + "id": "195", "metadata": {}, "outputs": [], "source": [ @@ -1786,16 +3371,20 @@ }, { "cell_type": "markdown", - "id": "116", + "id": "196", "metadata": {}, "source": [ - "### 2D buildings" + "### 2D Buildings, Transportation, and Other Themes\n", + "\n", + "Switch between specific Overture themes, such as `buildings`, `transportation`, `places`, or `addresses`, depending on the data focus. Each theme overlays relevant features with adjustable opacity for thematic visualization, providing easy customization for urban planning or transportation studies.\n", + "\n", + "Building theme:" ] }, { "cell_type": "code", "execution_count": null, - "id": "117", + "id": "197", "metadata": {}, "outputs": [], "source": [ @@ -1808,16 +3397,16 @@ }, { "cell_type": "markdown", - "id": "118", + "id": "198", "metadata": {}, "source": [ - "### Transportation" + "Transportation theme:" ] }, { "cell_type": "code", "execution_count": null, - "id": "119", + "id": "199", "metadata": {}, "outputs": [], "source": [ @@ -1830,16 +3419,16 @@ }, { "cell_type": "markdown", - "id": "120", + "id": "200", "metadata": {}, "source": [ - "### Places" + "Places theme:" ] }, { "cell_type": "code", "execution_count": null, - "id": "121", + "id": "201", "metadata": {}, "outputs": [], "source": [ @@ -1852,16 +3441,16 @@ }, { "cell_type": "markdown", - "id": "122", + "id": "202", "metadata": {}, "source": [ - "### Addresses" + "Addresses theme:" ] }, { "cell_type": "code", "execution_count": null, - "id": "123", + "id": "203", "metadata": {}, "outputs": [], "source": [ @@ -1874,16 +3463,16 @@ }, { "cell_type": "markdown", - "id": "124", + "id": "204", "metadata": {}, "source": [ - "### Base" + "Base theme:" ] }, { "cell_type": "code", "execution_count": null, - "id": "125", + "id": "205", "metadata": {}, "outputs": [], "source": [ @@ -1896,16 +3485,16 @@ }, { "cell_type": "markdown", - "id": "126", + "id": "206", "metadata": {}, "source": [ - "### Divisions" + "Divisions themem:" ] }, { "cell_type": "code", "execution_count": null, - "id": "127", + "id": "207", "metadata": {}, "outputs": [], "source": [ @@ -1918,714 +3507,634 @@ }, { "cell_type": "markdown", - "id": "128", + "id": "208", "metadata": {}, "source": [ - "## Add custom components\n", + "## Deck.GL Layers\n", + "\n", + "Integrate interactive, high-performance visualization layers using Deck.GL. Leafmap’s `add_deck_layer` method supports multiple Deck.GL layer types, including Grid, GeoJSON, and Arc layers.\n", "\n", - "You can add custom components to the map, including images, videos, text, color bar, and legend.\n", + "### Single Deck.GL Layer\n", "\n", - "### Add image" + "Add a `GridLayer` to visualize point data, such as the density of bike parking in San Francisco. Customize the grid cell size, elevation, and color to represent data density visually and interactively." ] }, { "cell_type": "code", "execution_count": null, - "id": "129", + "id": "209", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[0.349419, -1.80921], zoom=3, style=\"streets\")\n", - "image = \"https://upload.wikimedia.org/wikipedia/commons/7/7c/201408_cat.png\"\n", - "source = {\n", - " \"type\": \"geojson\",\n", - " \"data\": {\n", - " \"type\": \"FeatureCollection\",\n", - " \"features\": [\n", - " {\"type\": \"Feature\", \"geometry\": {\"type\": \"Point\", \"coordinates\": [0, 0]}}\n", - " ],\n", - " },\n", + "m = leafmap.Map(\n", + " style=\"positron\",\n", + " center=(-122.4, 37.74),\n", + " zoom=12,\n", + " pitch=40,\n", + ")\n", + "deck_grid_layer = {\n", + " \"@@type\": \"GridLayer\",\n", + " \"id\": \"GridLayer\",\n", + " \"data\": \"https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/sf-bike-parking.json\",\n", + " \"extruded\": True,\n", + " \"getPosition\": \"@@=COORDINATES\",\n", + " \"getColorWeight\": \"@@=SPACES\",\n", + " \"getElevationWeight\": \"@@=SPACES\",\n", + " \"elevationScale\": 4,\n", + " \"cellSize\": 200,\n", + " \"pickable\": True,\n", "}\n", "\n", - "layer = {\n", - " \"id\": \"points\",\n", - " \"type\": \"symbol\",\n", - " \"source\": \"point\",\n", - " \"layout\": {\n", - " \"icon-image\": \"cat\",\n", - " \"icon-size\": 0.25,\n", - " \"text-field\": \"I love kitty!\",\n", - " \"text-font\": [\"Open Sans Regular\"],\n", - " \"text-offset\": [0, 3],\n", - " \"text-anchor\": \"top\",\n", - " },\n", - "}\n", - "m.add_image(\"cat\", image)\n", - "m.add_source(\"point\", source)\n", - "m.add_layer(layer)\n", + "m.add_deck_layers([deck_grid_layer], tooltip=\"Number of points: {{ count }}\")\n", "m" ] }, { - "cell_type": "code", - "execution_count": null, - "id": "130", + "cell_type": "markdown", + "id": "210", "metadata": {}, - "outputs": [], "source": [ - "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", - "image = \"https://i.imgur.com/LmTETPX.png\"\n", - "m.add_image(image=image, position=\"bottom-right\")\n", - "m" + "### Multiple Deck.GL Layers\n", + "\n", + "Combine layers like `GeoJsonLayer` and `ArcLayer` for complex visualizations. For example:\n", + "1. Use `GeoJsonLayer` to show airports with varying point sizes based on significance.\n", + "2. Use `ArcLayer` to connect selected airports with London, coloring arcs to represent different paths." ] }, { "cell_type": "code", "execution_count": null, - "id": "131", + "id": "211", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", - "content = ''\n", - "m.add_html(content, bg_color=\"transparent\", position=\"bottom-right\")\n", - "m" + "url = \"https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_airports.geojson\"\n", + "data = leafmap.read_geojson(url)" ] }, { "cell_type": "code", "execution_count": null, - "id": "132", + "id": "212", "metadata": {}, "outputs": [], - "source": [] + "source": [ + "m = leafmap.Map(\n", + " style=\"positron\",\n", + " center=(0.45, 51.47),\n", + " zoom=4,\n", + " pitch=30,\n", + ")\n", + "deck_geojson_layer = {\n", + " \"@@type\": \"GeoJsonLayer\",\n", + " \"id\": \"airports\",\n", + " \"data\": data,\n", + " \"filled\": True,\n", + " \"pointRadiusMinPixels\": 2,\n", + " \"pointRadiusScale\": 2000,\n", + " \"getPointRadius\": \"@@=11 - properties.scalerank\",\n", + " \"getFillColor\": [200, 0, 80, 180],\n", + " \"autoHighlight\": True,\n", + " \"pickable\": True,\n", + "}\n", + "\n", + "deck_arc_layer = {\n", + " \"@@type\": \"ArcLayer\",\n", + " \"id\": \"arcs\",\n", + " \"data\": [\n", + " feature\n", + " for feature in data[\"features\"]\n", + " if feature[\"properties\"][\"scalerank\"] < 4\n", + " ],\n", + " \"getSourcePosition\": [-0.4531566, 51.4709959], # London\n", + " \"getTargetPosition\": \"@@=geometry.coordinates\",\n", + " \"getSourceColor\": [0, 128, 200],\n", + " \"getTargetColor\": [200, 0, 80],\n", + " \"getWidth\": 2,\n", + " \"pickable\": True,\n", + "}\n", + "\n", + "m.add_deck_layers(\n", + " [deck_geojson_layer, deck_arc_layer],\n", + " tooltip={\n", + " \"airports\": \"{{ &properties.name }}\",\n", + " \"arcs\": \"gps_code: {{ properties.gps_code }}\",\n", + " },\n", + ")\n", + "m" + ] }, { - "cell_type": "code", - "execution_count": null, - "id": "133", + "cell_type": "markdown", + "id": "213", "metadata": {}, - "outputs": [], "source": [ - "import numpy as np\n", - "\n", - "\n", - "# Generate the icon data\n", - "width = 64 # The image will be 64 pixels square\n", - "height = 64\n", - "bytes_per_pixel = 4 # Each pixel is represented by 4 bytes: red, green, blue, and alpha\n", - "data = np.zeros((width, width, bytes_per_pixel), dtype=np.uint8)\n", - "\n", - "for x in range(width):\n", - " for y in range(width):\n", - " data[y, x, 0] = int((y / width) * 255) # red\n", - " data[y, x, 1] = int((x / width) * 255) # green\n", - " data[y, x, 2] = 128 # blue\n", - " data[y, x, 3] = 255 # alpha\n", + "The result is a rich, interactive visualization that highlights both point data and relational data connections, useful for airport connectivity or hub-and-spoke modeling.\n", "\n", - "# Flatten the data array\n", - "flat_data = data.flatten()\n", - "\n", - "# Create the image dictionary\n", - "image_dict = {\n", - " \"width\": width,\n", - " \"height\": height,\n", - " \"data\": flat_data.tolist(),\n", - "}\n", "\n", - "m = leafmap.Map(center=[0, 0], zoom=1, style=\"streets\")\n", - "m.add_image(\"gradient\", image_dict)\n", - "source = {\n", - " \"type\": \"geojson\",\n", - " \"data\": {\n", - " \"type\": \"FeatureCollection\",\n", - " \"features\": [\n", - " {\"type\": \"Feature\", \"geometry\": {\"type\": \"Point\", \"coordinates\": [0, 0]}}\n", - " ],\n", - " },\n", - "}\n", + "## Google Earth Engine\n", "\n", - "layer = {\n", - " \"id\": \"points\",\n", - " \"type\": \"symbol\",\n", - " \"source\": \"point\",\n", - " \"layout\": {\"icon-image\": \"gradient\"},\n", - "}\n", + "Leafmap enables integration with the Google Earth Engine (GEE) Python API, allowing for powerful visualization of Earth Engine datasets directly on a Leafmap map.\n", "\n", - "m.add_source(\"point\", source)\n", - "m.add_layer(layer)\n", - "m" + "To add Earth Engine layers, initialize a map and use `add_ee_layer` to add specific datasets, such as ESA WorldCover data. A legend can be included using `add_legend` to provide a visual reference." ] }, { "cell_type": "code", "execution_count": null, - "id": "134", + "id": "214", "metadata": {}, "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "135", - "metadata": {}, "source": [ - "### Add text" + "m = leafmap.Map(\n", + " center=[-120.4482, 38.0399], zoom=13, pitch=60, bearing=30, style=\"3d-terrain\"\n", + ")\n", + "m.add_ee_layer(asset_id=\"ESA/WorldCover/v200\", opacity=0.5)\n", + "m.add_legend(builtin_legend=\"ESA_WorldCover\", title=\"ESA Landcover\")\n", + "m.add_layer_control()\n", + "m" ] }, { "cell_type": "code", "execution_count": null, - "id": "136", + "id": "215", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"streets\")\n", - "text = \"Hello World\"\n", - "m.add_text(text, fontsize=20, position=\"bottom-right\")\n", - "text2 = \"Awesome Text!\"\n", - "m.add_text(text2, fontsize=25, bg_color=\"rgba(255, 255, 255, 0.8)\", position=\"top-left\")\n", - "m" + "m.layer_interact()" ] }, { "cell_type": "markdown", - "id": "137", + "id": "216", "metadata": {}, "source": [ - "### Add GIF" + "You can overlay Earth Engine data with other 3D elements, like buildings, to create a multi-layered, interactive map. If you have an Earth Engine account, authenticate and initialize Earth Engine in your notebook by uncommenting the relevant code." ] }, { "cell_type": "code", "execution_count": null, - "id": "138", + "id": "217", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", - "image = \"https://i.imgur.com/KeiAsTv.gif\"\n", - "m.add_image(image=image, width=250, height=250, position=\"bottom-right\")\n", - "text = \"I love sloth!🦥\"\n", - "m.add_text(text, fontsize=35, padding=\"20px\")\n", - "image2 = \"https://i.imgur.com/kZC2tpr.gif\"\n", - "m.add_image(image=image2, bg_color=\"transparent\", position=\"bottom-left\")\n", + "m = leafmap.Map(\n", + " center=[-74.012998, 40.70414], zoom=15.6, pitch=60, bearing=30, style=\"3d-terrain\"\n", + ")\n", + "m.add_ee_layer(asset_id=\"ESA/WorldCover/v200\", opacity=0.5)\n", + "m.add_3d_buildings()\n", + "m.add_legend(builtin_legend=\"ESA_WorldCover\", title=\"ESA Landcover\")\n", "m" ] }, { "cell_type": "markdown", - "id": "139", + "id": "218", "metadata": {}, "source": [ - "### Add HTML" + "If you have an Earth Engine, you can uncomment the first two code blocks to add any Earth Engine datasets." ] }, { "cell_type": "code", "execution_count": null, - "id": "140", + "id": "219", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", - "html = \"\"\"\n", - "\n", - "\n", - "\n", - "\n", - "🚀\n", - "

I will display 🚁

\n", - "

I will display 🚂

\n", + "# import ee\n", "\n", - "\n", - "\n", - "\"\"\"\n", - "m.add_html(html, bg_color=\"transparent\")\n", - "m" + "# ee.Authenticate()\n", + "# ee.Initialize(project=\"YOUR-PROJECT-ID\")" ] }, { - "cell_type": "markdown", - "id": "141", + "cell_type": "code", + "execution_count": null, + "id": "220", "metadata": {}, + "outputs": [], "source": [ - "### Add colorbar" + "# m = leafmap.Map(center=[-120.4482, 38.03994], zoom=13, pitch=60, bearing=30, style=\"3d-terrain\")\n", + "# dataset = ee.ImageCollection(\"ESA/WorldCover/v200\").first()\n", + "# vis_params = {\"bands\": [\"Map\"]}\n", + "# m.add_ee_layer(dataset, vis_params, name=\"ESA Worldcover\", opacity=0.5)\n", + "# m.add_legend(builtin_legend=\"ESA_WorldCover\", title=\"ESA Landcover\")\n", + "# m.add_layer_control()\n", + "# m" ] }, { - "cell_type": "code", - "execution_count": null, - "id": "142", + "cell_type": "markdown", + "id": "221", "metadata": {}, - "outputs": [], "source": [ - "dem = \"https://github.com/opengeos/datasets/releases/download/raster/srtm90.tif\"" + "## Animations\n", + "\n", + "### Animate a Line\n", + "\n", + "Using Leafmap’s animation capabilities, you can animate a line by updating the coordinates of a GeoJSON line feature in real-time. The sample includes data loaded from a CSV file, which is sorted and plotted sequentially to show the line’s movement." ] }, { "cell_type": "code", "execution_count": null, - "id": "143", + "id": "222", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(style=\"streets\")\n", - "m.add_cog_layer(\n", - " dem,\n", - " name=\"DEM\",\n", - " colormap_name=\"terrain\",\n", - " rescale=\"0, 4000\",\n", - " fit_bounds=True,\n", - " nodata=0,\n", - ")\n", - "m.add_colorbar(\n", - " cmap=\"terrain\", vmin=0, vmax=4000, label=\"Elevation (m)\", position=\"bottom-right\"\n", - ")\n", - "m" + "import time\n", + "import pandas as pd" ] }, { "cell_type": "code", "execution_count": null, - "id": "144", + "id": "223", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(style=\"streets\")\n", - "m.add_cog_layer(\n", - " dem,\n", - " name=\"DEM\",\n", - " colormap_name=\"terrain\",\n", - " rescale=\"0, 4000\",\n", - " nodata=0,\n", - " fit_bounds=True,\n", - ")\n", - "m.add_colorbar(\n", - " cmap=\"terrain\",\n", - " vmin=0,\n", - " vmax=4000,\n", - " label=\"Elevation (m)\",\n", - " position=\"bottom-right\",\n", - " transparent=True,\n", - ")\n", - "m" + "url = \"https://github.com/opengeos/datasets/releases/download/world/animated_line_data.csv\"\n", + "df = pd.read_csv(url)\n", + "df_sample = df.sample(n=1000, random_state=1).sort_index()\n", + "df_sample.loc[len(df_sample)] = df.iloc[-1]\n", + "df_sample.head()" ] }, { "cell_type": "code", "execution_count": null, - "id": "145", + "id": "224", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(style=\"streets\")\n", - "m.add_cog_layer(\n", - " dem,\n", - " name=\"DEM\",\n", - " colormap_name=\"terrain\",\n", - " rescale=\"0, 4000\",\n", - " nodata=0,\n", - " fit_bounds=True,\n", - ")\n", - "m.add_colorbar(\n", - " cmap=\"terrain\",\n", - " vmin=0,\n", - " vmax=4000,\n", - " label=\"Elevation (m)\",\n", - " position=\"bottom-right\",\n", - " width=0.2,\n", - " height=3,\n", - " orientation=\"vertical\",\n", - ")\n", + "m = leafmap.Map(center=[0, 0], zoom=0.5, style=\"liberty\")\n", + "geojson = {\n", + " \"type\": \"FeatureCollection\",\n", + " \"features\": [\n", + " {\"type\": \"Feature\", \"geometry\": {\"type\": \"LineString\", \"coordinates\": [[0, 0]]}}\n", + " ],\n", + "}\n", + "source = {\"type\": \"geojson\", \"data\": geojson}\n", + "m.add_source(\"line\", source)\n", + "layer = {\n", + " \"id\": \"line-animation\",\n", + " \"type\": \"line\",\n", + " \"source\": \"line\",\n", + " \"layout\": {\"line-cap\": \"round\", \"line-join\": \"round\"},\n", + " \"paint\": {\"line-color\": \"#ed6498\", \"line-width\": 5, \"line-opacity\": 0.8},\n", + "}\n", + "m.add_layer(layer)\n", "m" ] }, - { - "cell_type": "markdown", - "id": "146", - "metadata": {}, - "source": [ - "### Add legend" - ] - }, { "cell_type": "code", "execution_count": null, - "id": "147", + "id": "225", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", - "m.add_basemap(\"Esri.WorldImagery\")\n", - "url = \"https://www.mrlc.gov/geoserver/mrlc_display/NLCD_2021_Land_Cover_L48/wms\"\n", - "layers = \"NLCD_2021_Land_Cover_L48\"\n", - "m.add_wms_layer(url, layers=layers, name=\"NLCD 2021\")\n", - "m.add_legend(\n", - " title=\"NLCD Land Cover Type\",\n", - " builtin_legend=\"NLCD\",\n", - " bg_color=\"rgba(255, 255, 255, 0.5)\",\n", - " position=\"bottom-left\",\n", - ")\n", - "m" + "run_times = 2\n", + "for i in range(run_times):\n", + " geojson[\"features\"][0][\"geometry\"][\"coordinates\"] = [[0, 0]]\n", + " for row in df_sample.itertuples():\n", + " time.sleep(0.005)\n", + " geojson[\"features\"][0][\"geometry\"][\"coordinates\"].append([row.x, row.y])\n", + " m.set_data(\"line\", geojson)" ] }, { - "cell_type": "code", - "execution_count": null, - "id": "148", + "cell_type": "markdown", + "id": "226", "metadata": {}, - "outputs": [], "source": [ - "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", - "m.add_basemap(\"Esri.WorldImagery\")\n", - "url = \"https://fwspublicservices.wim.usgs.gov/wetlandsmapservice/services/Wetlands/MapServer/WMSServer\"\n", - "m.add_wms_layer(url, layers=\"1\", name=\"NWI\", opacity=0.6)\n", - "m.add_layer_control()\n", - "m.add_legend(builtin_legend=\"NWI\", title=\"Wetland Type\")\n", - "m" + "### Animate the Map Camera Around a Point\n", + "\n", + "Control the map camera's rotation, zoom, and angle around a given point to create a smooth animation effect. This technique is especially useful for visualizing cityscapes or other 3D environments by making buildings appear dynamic." ] }, { "cell_type": "code", "execution_count": null, - "id": "149", + "id": "227", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"positron\")\n", - "m.add_basemap(\"Esri.WorldImagery\")\n", - "url = \"https://www.mrlc.gov/geoserver/mrlc_display/NLCD_2021_Land_Cover_L48/wms\"\n", - "layers = \"NLCD_2021_Land_Cover_L48\"\n", - "m.add_wms_layer(url, layers=layers, name=\"NLCD 2021\")\n", - "\n", - "legend_dict = {\n", - " \"11 Open Water\": \"466b9f\",\n", - " \"12 Perennial Ice/Snow\": \"d1def8\",\n", - " \"21 Developed, Open Space\": \"dec5c5\",\n", - " \"22 Developed, Low Intensity\": \"d99282\",\n", - " \"23 Developed, Medium Intensity\": \"eb0000\",\n", - " \"24 Developed High Intensity\": \"ab0000\",\n", - " \"31 Barren Land (Rock/Sand/Clay)\": \"b3ac9f\",\n", - " \"41 Deciduous Forest\": \"68ab5f\",\n", - " \"42 Evergreen Forest\": \"1c5f2c\",\n", - " \"43 Mixed Forest\": \"b5c58f\",\n", - " \"51 Dwarf Scrub\": \"af963c\",\n", - " \"52 Shrub/Scrub\": \"ccb879\",\n", - " \"71 Grassland/Herbaceous\": \"dfdfc2\",\n", - " \"72 Sedge/Herbaceous\": \"d1d182\",\n", - " \"73 Lichens\": \"a3cc51\",\n", - " \"74 Moss\": \"82ba9e\",\n", - " \"81 Pasture/Hay\": \"dcd939\",\n", - " \"82 Cultivated Crops\": \"ab6c28\",\n", - " \"90 Woody Wetlands\": \"b8d9eb\",\n", - " \"95 Emergent Herbaceous Wetlands\": \"6c9fb8\",\n", + "m = leafmap.Map(center=[-87.62712, 41.89033], zoom=15, pitch=45, style=\"streets\")\n", + "layers = m.get_style_layers()\n", + "for layer in layers:\n", + " if layer[\"type\"] == \"symbol\" and (\"text-field\" in layer[\"layout\"]):\n", + " m.remove_layer(layer[\"id\"])\n", + "layer = {\n", + " \"id\": \"3d-buildings\",\n", + " \"source\": \"composite\",\n", + " \"source-layer\": \"building\",\n", + " \"filter\": [\"==\", \"extrude\", \"true\"],\n", + " \"type\": \"fill-extrusion\",\n", + " \"min_zoom\": 15,\n", + " \"paint\": {\n", + " \"fill-extrusion-color\": \"#aaa\",\n", + " \"fill-extrusion-height\": [\n", + " \"interpolate\",\n", + " [\"linear\"],\n", + " [\"zoom\"],\n", + " 15,\n", + " 0,\n", + " 15.05,\n", + " [\"get\", \"height\"],\n", + " ],\n", + " \"fill-extrusion-base\": [\n", + " \"interpolate\",\n", + " [\"linear\"],\n", + " [\"zoom\"],\n", + " 15,\n", + " 0,\n", + " 15.05,\n", + " [\"get\", \"min_height\"],\n", + " ],\n", + " \"fill-extrusion-opacity\": 0.6,\n", + " },\n", "}\n", - "m.add_legend(\n", - " title=\"NLCD Land Cover Type\",\n", - " legend_dict=legend_dict,\n", - " bg_color=\"rgba(255, 255, 255, 0.5)\",\n", - " position=\"bottom-left\",\n", - ")\n", + "m.add_layer(layer)\n", "m" ] }, { "cell_type": "markdown", - "id": "150", + "id": "228", "metadata": {}, "source": [ - "### Add video\n", + "### Animate a Point\n", "\n", - "The `urls` value is an array. For each URL in the array, a video element source will be created. To support the video across browsers, supply URLs in multiple formats.\n", - "The `coordinates` array contains [longitude, latitude] pairs for the video corners listed in clockwise order: top left, top right, bottom right, bottom left." + "Animate a point along a circular path by computing points on a circle and updating the map. This is ideal for showing circular motion on the map, and can be customized for duration and frame rate to control the animation speed." ] }, { "cell_type": "code", "execution_count": null, - "id": "151", + "id": "229", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(\n", - " center=[-122.514426, 37.562984], zoom=17, bearing=-96, style=\"satellite\"\n", - ")\n", - "urls = [\n", - " \"https://static-assets.mapbox.com/mapbox-gl-js/drone.mp4\",\n", - " \"https://static-assets.mapbox.com/mapbox-gl-js/drone.webm\",\n", - "]\n", - "coordinates = [\n", - " [-122.51596391201019, 37.56238816766053],\n", - " [-122.51467645168304, 37.56410183312965],\n", - " [-122.51309394836426, 37.563391708549425],\n", - " [-122.51423120498657, 37.56161849366671],\n", - "]\n", - "m.add_video(urls, coordinates)\n", - "m.add_layer_control()\n", - "m" + "for degree in range(0, 180, 1):\n", + " m.rotate_to(degree, {\"duration\": 0})\n", + " time.sleep(0.1)" ] }, { "cell_type": "code", "execution_count": null, - "id": "152", + "id": "230", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(center=[-115, 25], zoom=4, style=\"satellite\")\n", - "urls = [\n", - " \"https://data.opengeos.org/patricia_nasa.mp4\",\n", - " \"https://data.opengeos.org/patricia_nasa.webm\",\n", - "]\n", - "coordinates = [\n", - " [-130, 32],\n", - " [-100, 32],\n", - " [-100, 13],\n", - " [-130, 13],\n", - "]\n", - "m.add_video(urls, coordinates)\n", - "m.add_layer_control()\n", - "m" + "import math" ] }, { - "cell_type": "markdown", - "id": "153", + "cell_type": "code", + "execution_count": null, + "id": "231", "metadata": {}, + "outputs": [], "source": [ - "## Deck.GL layers\n", - "\n", - "Deck.GL layers can be added to the map using the `add_deck_layer` method.\n", - "\n", - "### Single Deck.GL layer" + "def point_on_circle(angle, radius):\n", + " return {\n", + " \"type\": \"Point\",\n", + " \"coordinates\": [math.cos(angle) * radius, math.sin(angle) * radius],\n", + " }" ] }, { "cell_type": "code", "execution_count": null, - "id": "154", + "id": "232", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(\n", - " style=\"positron\",\n", - " center=(-122.4, 37.74),\n", - " zoom=12,\n", - " pitch=40,\n", - ")\n", - "deck_grid_layer = {\n", - " \"@@type\": \"GridLayer\",\n", - " \"id\": \"GridLayer\",\n", - " \"data\": \"https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/sf-bike-parking.json\",\n", - " \"extruded\": True,\n", - " \"getPosition\": \"@@=COORDINATES\",\n", - " \"getColorWeight\": \"@@=SPACES\",\n", - " \"getElevationWeight\": \"@@=SPACES\",\n", - " \"elevationScale\": 4,\n", - " \"cellSize\": 200,\n", - " \"pickable\": True,\n", + "m = leafmap.Map(center=[0, 0], zoom=2, style=\"liberty\")\n", + "radius = 20\n", + "source = {\"type\": \"geojson\", \"data\": point_on_circle(0, radius)}\n", + "m.add_source(\"point\", source)\n", + "layer = {\n", + " \"id\": \"point\",\n", + " \"source\": \"point\",\n", + " \"type\": \"circle\",\n", + " \"paint\": {\"circle-radius\": 10, \"circle-color\": \"#007cbf\"},\n", "}\n", - "\n", - "m.add_deck_layers([deck_grid_layer], tooltip=\"Number of points: {{ count }}\")\n", + "m.add_layer(layer)\n", "m" ] }, - { - "cell_type": "markdown", - "id": "155", - "metadata": {}, - "source": [ - "### Multiple Deck.GL layers" - ] - }, { "cell_type": "code", "execution_count": null, - "id": "156", + "id": "233", "metadata": {}, "outputs": [], "source": [ - "import requests" + "def animate_marker(duration, frame_rate, radius):\n", + " start_time = time.time()\n", + " while (time.time() - start_time) < duration:\n", + " timestamp = (time.time() - start_time) * 1000 # Convert to milliseconds\n", + " angle = timestamp / 1000 # Divisor controls the animation speed\n", + " point = point_on_circle(angle, radius)\n", + " m.set_data(\"point\", point)\n", + " # Wait for the next frame\n", + " time.sleep(1 / frame_rate)" ] }, { "cell_type": "code", "execution_count": null, - "id": "157", + "id": "234", "metadata": {}, "outputs": [], "source": [ - "data = requests.get(\n", - " \"https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_airports.geojson\"\n", - ").json()" + "duration = 10 # Duration of the animation in seconds\n", + "frame_rate = 30 # Frames per second" ] }, { "cell_type": "code", "execution_count": null, - "id": "158", + "id": "235", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(\n", - " style=\"positron\",\n", - " center=(0.45, 51.47),\n", - " zoom=4,\n", - " pitch=30,\n", - ")\n", - "deck_geojson_layer = {\n", - " \"@@type\": \"GeoJsonLayer\",\n", - " \"id\": \"airports\",\n", - " \"data\": data,\n", - " \"filled\": True,\n", - " \"pointRadiusMinPixels\": 2,\n", - " \"pointRadiusScale\": 2000,\n", - " \"getPointRadius\": \"@@=11 - properties.scalerank\",\n", - " \"getFillColor\": [200, 0, 80, 180],\n", - " \"autoHighlight\": True,\n", - " \"pickable\": True,\n", - "}\n", - "\n", - "deck_arc_layer = {\n", - " \"@@type\": \"ArcLayer\",\n", - " \"id\": \"arcs\",\n", - " \"data\": [\n", - " feature\n", - " for feature in data[\"features\"]\n", - " if feature[\"properties\"][\"scalerank\"] < 4\n", - " ],\n", - " \"getSourcePosition\": [-0.4531566, 51.4709959], # London\n", - " \"getTargetPosition\": \"@@=geometry.coordinates\",\n", - " \"getSourceColor\": [0, 128, 200],\n", - " \"getTargetColor\": [200, 0, 80],\n", - " \"getWidth\": 2,\n", - " \"pickable\": True,\n", - "}\n", - "\n", - "m.add_deck_layers(\n", - " [deck_geojson_layer, deck_arc_layer],\n", - " tooltip={\n", - " \"airports\": \"{{ &properties.name }}\",\n", - " \"arcs\": \"gps_code: {{ properties.gps_code }}\",\n", - " },\n", - ")\n", - "m" + "animate_marker(duration, frame_rate, radius)" ] }, { "cell_type": "markdown", - "id": "159", + "id": "236", "metadata": {}, "source": [ - "## Google Earth Engine\n", + "### Animate a Point Along a Route\n", "\n", - "You can use the Earth Engine Python API to load and visualize Earth Engine data." + "Create a point that follows a route specified by GeoJSON coordinates. For added realism, include rotation properties to simulate the direction of movement along the path. This animation is useful for tracking paths, such as vehicle or drone routes." ] }, { "cell_type": "code", "execution_count": null, - "id": "160", + "id": "237", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(\n", - " center=[-120.4482, 38.0399], zoom=13, pitch=60, bearing=30, style=\"3d-terrain\"\n", - ")\n", - "m.add_ee_layer(asset_id=\"ESA/WorldCover/v200\", opacity=0.5)\n", - "m.add_legend(builtin_legend=\"ESA_WorldCover\", title=\"ESA Landcover\")\n", - "m.add_layer_control()\n", + "m = leafmap.Map(center=[-100, 40], zoom=3, style=\"streets\")\n", + "url = \"https://github.com/opengeos/datasets/releases/download/us/arc_with_bearings.geojson\"\n", + "geojson = leafmap.read_geojson(url)\n", + "bearings = geojson[\"features\"][0][\"properties\"][\"bearings\"]\n", + "coordinates = geojson[\"features\"][0][\"geometry\"][\"coordinates\"][:-1]\n", + "m.add_geojson(geojson, name=\"route\")\n", + "\n", + "origin = [-122.414, 37.776]\n", + "destination = [-77.032, 38.913]\n", + "\n", + "point = {\n", + " \"type\": \"FeatureCollection\",\n", + " \"features\": [\n", + " {\n", + " \"type\": \"Feature\",\n", + " \"properties\": {},\n", + " \"geometry\": {\"type\": \"Point\", \"coordinates\": origin},\n", + " }\n", + " ],\n", + "}\n", + "source = {\"type\": \"geojson\", \"data\": point}\n", + "m.add_source(\"point\", source)\n", + "layer = {\n", + " \"id\": \"point\",\n", + " \"source\": \"point\",\n", + " \"type\": \"symbol\",\n", + " \"layout\": {\n", + " \"icon-image\": \"airport_15\",\n", + " \"icon-rotate\": [\"get\", \"bearing\"],\n", + " \"icon-rotation-alignment\": \"map\",\n", + " \"icon-overlap\": \"always\",\n", + " \"icon-ignore-placement\": True,\n", + " },\n", + "}\n", + "m.add_layer(layer)\n", "m" ] }, { "cell_type": "code", "execution_count": null, - "id": "161", + "id": "238", "metadata": {}, "outputs": [], "source": [ - "m.layer_interact()" + "for index, coordinate in enumerate(coordinates):\n", + " point[\"features\"][0][\"geometry\"][\"coordinates\"] = coordinate\n", + " point[\"features\"][0][\"properties\"][\"bearing\"] = bearings[index]\n", + " m.set_data(\"point\", point)\n", + " time.sleep(0.05)" ] }, { "cell_type": "markdown", - "id": "162", + "id": "239", "metadata": {}, "source": [ - "We can also overlay other data layers on top of Earth Engine data layers." + "### Update a Feature in Real-Time\n", + "\n", + "For applications such as tracking or tracing a path in real time, load data from a source like GeoDataFrame, append coordinates incrementally to a line feature, and update the map display as the path extends." ] }, { "cell_type": "code", "execution_count": null, - "id": "163", + "id": "240", "metadata": {}, "outputs": [], "source": [ - "m = leafmap.Map(\n", - " center=[-74.012998, 40.70414], zoom=15.6, pitch=60, bearing=30, style=\"3d-terrain\"\n", - ")\n", - "m.add_ee_layer(asset_id=\"ESA/WorldCover/v200\", opacity=0.5)\n", - "m.add_3d_buildings()\n", - "m.add_legend(builtin_legend=\"ESA_WorldCover\", title=\"ESA Landcover\")\n", + "import geopandas as gpd" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "241", + "metadata": {}, + "outputs": [], + "source": [ + "m = leafmap.Map(center=[-122.019807, 45.632433], zoom=14, pitch=60, style=\"3d-terrain\")\n", "m" ] }, { - "cell_type": "markdown", - "id": "164", + "cell_type": "code", + "execution_count": null, + "id": "242", "metadata": {}, + "outputs": [], "source": [ - "If you have an Earth Engine, you can uncomment the first two code blocks to add any Earth Engine datasets." + "url = \"https://maplibre.org/maplibre-gl-js/docs/assets/hike.geojson\"\n", + "gdf = gpd.read_file(url)\n", + "coordinates = list(gdf.geometry[0].coords)\n", + "print(coordinates[:5])" ] }, { "cell_type": "code", "execution_count": null, - "id": "165", + "id": "243", "metadata": {}, "outputs": [], "source": [ - "# import ee\n", - "# ee.Initialize(project=\"YOUR-PROJECT-ID\")" + "source = {\n", + " \"type\": \"geojson\",\n", + " \"data\": {\n", + " \"type\": \"Feature\",\n", + " \"geometry\": {\"type\": \"LineString\", \"coordinates\": [coordinates[0]]},\n", + " },\n", + "}\n", + "m.add_source(\"trace\", source)\n", + "layer = {\n", + " \"id\": \"trace\",\n", + " \"type\": \"line\",\n", + " \"source\": \"trace\",\n", + " \"paint\": {\"line-color\": \"yellow\", \"line-opacity\": 0.75, \"line-width\": 5},\n", + "}\n", + "m.add_layer(layer)\n", + "m.jump_to({\"center\": coordinates[0], \"zoom\": 14})\n", + "m.set_pitch(30)" ] }, { "cell_type": "code", "execution_count": null, - "id": "166", + "id": "244", "metadata": {}, "outputs": [], "source": [ - "# m = leafmap.Map(center=[-120.4482, 38.03994], zoom=13, pitch=60, bearing=30, style=\"3d-terrain\")\n", - "# dataset = ee.ImageCollection(\"ESA/WorldCover/v200\").first()\n", - "# vis_params = {\"bands\": [\"Map\"]}\n", - "# m.add_ee_layer(dataset, vis_params, name=\"ESA Worldcover\", opacity=0.5)\n", - "# m.add_legend(builtin_legend=\"ESA_WorldCover\", title=\"ESA Landcover\")\n", - "# m.add_layer_control()\n", - "# m" + "for coord in coordinates:\n", + " time.sleep(0.005)\n", + " source[\"data\"][\"geometry\"][\"coordinates\"].append(coord)\n", + " m.set_data(\"trace\", source[\"data\"])\n", + " m.pan_to(coord)" ] }, { "cell_type": "markdown", - "id": "167", + "id": "245", "metadata": {}, "source": [ "## To HTML\n", "\n", - "To export the map as an HTML file, use the `to_html` method. To avoid exposing your private API key, you should create a public API key and restrict it to your website domain." + "Export the final map to HTML using the `to_html` method. This allows you to share interactive maps online while keeping your private API keys secure. Create public API keys restricted to your website’s domain for safety. Customize the HTML output, including dimensions, title, and embedding options." ] }, { "cell_type": "code", "execution_count": null, - "id": "168", + "id": "246", "metadata": {}, "outputs": [], "source": [ @@ -2637,7 +4146,7 @@ { "cell_type": "code", "execution_count": null, - "id": "169", + "id": "247", "metadata": {}, "outputs": [], "source": [ @@ -2658,7 +4167,7 @@ { "cell_type": "code", "execution_count": null, - "id": "170", + "id": "248", "metadata": {}, "outputs": [], "source": [ @@ -2677,6 +4186,16 @@ ")\n", "m" ] + }, + { + "cell_type": "markdown", + "id": "249", + "metadata": {}, + "source": [ + "## Summary\n", + "\n", + "In this lecture, we explored the functionality of the MapLibre library for creating and customizing interactive maps in Python. We covered how to build a map from scratch, add controls, and manage different basemaps. Additionally, we explored more complex visualizations, including 3D building and terrain views, layer customization, and data integration with GeoJSON and raster formats. By understanding and applying these techniques, students are now equipped to develop dynamic geospatial visualizations using MapLibre, enhancing both analytical and presentation capabilities in their GIS projects." + ] } ], "metadata": { diff --git a/book/geospatial/maplibre.md b/book/geospatial/maplibre.md index 2ce81db..871905f 100644 --- a/book/geospatial/maplibre.md +++ b/book/geospatial/maplibre.md @@ -17,11 +17,18 @@ kernelspec: ## Overview -The notebook demonstrates how to create 3D maps using the [MapLibre](https://github.com/eodaGmbH/py-maplibregl) Python package. The examples shown in this notebook are based on the [MapLibre documentation](https://eodagmbh.github.io/py-maplibregl/examples/vancouver_blocks/). +This lecture introduces the [MapLibre](https://github.com/eodaGmbH/py-maplibregl) Python package, a flexible open-source mapping Python package that allows users to create interactive and customizable 3D and 2D maps in Python. By leveraging the MapLibre library, GIS developers can visualize geospatial data with a variety of customization options and mapping styles. The notebook demonstrates essential concepts like creating interactive maps, customizing basemaps, adding various data layers, and implementing map controls for enhanced functionality. Additionally, advanced features, such as 3D building visualization and layer control, provide students with practical tools for real-world geospatial data analysis and visualization. -## Learning Objectives +## Learning Outcomes -TBA. +By the end of this lecture, students will be able to: + +1. Set up and install MapLibre for geospatial visualization in Python. +2. Create basic interactive maps and apply different basemap styles. +3. Customize map features, including markers, lines, polygons, and map controls. +4. Utilize advanced features such as 3D buildings and choropleth maps. +5. Integrate and manage multiple data layers, including GeoJSON, raster, and vector layers. +6. Export map visualizations as standalone HTML files for sharing and deployment. ## Useful Resources @@ -29,55 +36,57 @@ TBA. - Videos: https://bit.ly/maplibre - Demos: https://maps.gishub.org -## Installation +## Installation and Setup -Uncomment the following line to install the required Python packages. +To install the required packages, uncomment and run the line below. ```{code-cell} ipython3 # %pip install -U "leafmap[maplibre]" ``` -Import the maplibre mapping backend. +Once installed, import the `maplibregl` backend from the `leafmap` package: ```{code-cell} ipython3 import leafmap.maplibregl as leafmap ``` -## Set up API Key - -To run this notebook, you need to set up a MapTiler API key. You can get a free API key by signing up at [https://cloud.maptiler.com/](https://cloud.maptiler.com/). - -```{code-cell} ipython3 -# import os -# os.environ["MAPTILER_KEY"] = "YOUR_API_KEY" -``` - -## Create interactive maps +## Creating Interactive Maps -### Create a simple map +### Basic Map Setup -Let's create a simple interactive map using Leafmap. +Let’s start by creating a simple interactive map with default settings. This basic setup provides a blank canvas on which you can add data layers, controls, and other customizations. ```{code-cell} ipython3 m = leafmap.Map() m ``` -You can customize the map by specifying map center [lon, lat], zoom level, pitch, and bearing. +### Customizing the Map's Center and Zoom Level + +You can specify the map’s center (latitude and longitude), zoom level, pitch, and bearing for a more focused view. These parameters help direct the user's attention to specific areas. ```{code-cell} ipython3 m = leafmap.Map(center=[-100, 40], zoom=3, pitch=0, bearing=0) m ``` -To customize the basemap, you can specify the `style` parameter. It can be an URL or a string, such as `dark-matter`, `positron`, `voyager`, `liberty`, `demotiles`. +### Choosing a Basemap Style + +MapLibre supports several pre-defined basemap styles such as `dark-matter`, `positron`, `voyager`, `liberty`, `demotiles`. You can also use custom basemap URLs for unique styling. ```{code-cell} ipython3 m = leafmap.Map(style="positron") m ``` -To create a map with a background color, use `style="background-"`, such as `background-lightgray` and `background-green`. +```{code-cell} ipython3 +m = leafmap.Map(style="liberty") +m +``` + +### Adding Background Colors + +Background color styles, such as `background-lightgray` and `background-green`, are helpful for simple or thematic maps where color-coding is needed. ```{code-cell} ipython3 m = leafmap.Map(style="background-lightgray") @@ -92,9 +101,21 @@ m = leafmap.Map(style=style) m ``` -### Add map controls +## Adding Map Controls + +Map controls enhance the usability of the map by allowing users to interact in various ways, adding elements like scale bars, zoom tools, and drawing options. -The control to add to the map. Can be one of the following: `scale`, `fullscreen`, `geolocate`, `navigation`. +### Available Controls + +- **Scale**: Adds a scale bar to indicate the map’s scale. +- **Fullscreen**: Expands the map to a full-screen view for better focus. +- **Geolocate**: Centers the map based on the user’s current location, if available. +- **Navigation**: Provides zoom controls and a compass for reorientation. +- **Draw**: Allows users to draw and edit shapes on the map. + +### Adding Geolocate Control + +The Geolocate control centers the map based on the user’s current location, a helpful feature for location-based applications. ```{code-cell} ipython3 m = leafmap.Map() @@ -102,13 +123,126 @@ m.add_control("geolocate", position="top-left") m ``` -### Add basemaps +### Adding Fullscreen Control + +Fullscreen control enables users to expand the map to full screen, enhancing focus and visual clarity. This is especially useful when viewing complex or large datasets. + +```{code-cell} ipython3 +m = leafmap.Map(center=[11.255, 43.77], zoom=13, style="streets", controls={}) +m.add_control("fullscreen", position="top-right") +m +``` + +### Adding Navigation Control + +The Navigation control provides buttons for zooming and reorienting the map, improving the user's ability to navigate efficiently. + +```{code-cell} ipython3 +m = leafmap.Map(center=[11.255, 43.77], zoom=13, style="streets", controls={}) +m.add_control("navigation", position="top-left") +m +``` + +### Adding Draw Control + +The Draw control enables users to interact with the map by adding shapes such as points, lines, and polygons. This control is essential for tasks requiring spatial data input directly on the map. + +```{code-cell} ipython3 +m = leafmap.Map(center=[-100, 40], zoom=3, style="positron") +m.add_draw_control(position="top-left") +m +``` + +You can configure the Draw control to activate specific tools, like polygon, line, or point drawing, while also enabling or disabling a "trash" button to remove unwanted shapes. + +```{code-cell} ipython3 +from maplibre.plugins import MapboxDrawControls, MapboxDrawOptions +``` + +```{code-cell} ipython3 +m = leafmap.Map(center=[-100, 40], zoom=3, style="positron") +draw_options = MapboxDrawOptions( + display_controls_default=False, + controls=MapboxDrawControls(polygon=True, line_string=True, point=True, trash=True), +) +m.add_draw_control(draw_options) +m +``` + +Additionally, you can load a GeoJSON FeatureCollection into the Draw control, which will allow users to view, edit, or interact with pre-defined geographical features, such as boundaries or points of interest. + +```{code-cell} ipython3 +m = leafmap.Map(center=[-100, 40], zoom=3, style="positron") +geojson = { + "type": "FeatureCollection", + "features": [ + { + "id": "abc", + "type": "Feature", + "properties": {}, + "geometry": { + "coordinates": [ + [ + [-119.08, 45.95], + [-119.79, 42.08], + [-107.28, 41.43], + [-108.15, 46.44], + [-119.08, 45.95], + ] + ], + "type": "Polygon", + }, + }, + { + "id": "xyz", + "type": "Feature", + "properties": {}, + "geometry": { + "coordinates": [ + [ + [-103.87, 38.08], + [-108.54, 36.44], + [-106.25, 33.00], + [-99.91, 31.79], + [-96.82, 35.48], + [-98.80, 37.77], + [-103.87, 38.08], + ] + ], + "type": "Polygon", + }, + }, + ], +} +m.add_draw_control(position="top-left", geojson=geojson) +m +``` + +Two key methods for accessing drawn features: + +- **Selected Features**: Accesses only the currently selected features. +- **All Features**: Accesses all features added, regardless of selection, giving you full control over the spatial data on the map. + +```{code-cell} ipython3 +m.draw_features_selected +``` + +```{code-cell} ipython3 +m.draw_feature_collection_all +``` + +## Add Layers + +Adding layers to a map enhances the data it presents, allowing different types of basemaps, tile layers, and thematic overlays to be combined for in-depth analysis. -You can add basemaps to the map using the `add_basemap` method. +### Adding Basemaps + +Basemaps provide a geographical context for the map. Using the `add_basemap` method, you can select from various basemaps, including `OpenTopoMap` and `Esri.WorldImagery`. Adding a layer control allows users to switch between multiple basemaps interactively. ```{code-cell} ipython3 m = leafmap.Map() m.add_basemap("OpenTopoMap") +m.add_layer_control() m ``` @@ -121,15 +255,15 @@ m = leafmap.Map() m ``` -To add basemaps interactively, use the `add_basemap` method without specifying the `basemap` parameter. +You can also add basemaps interactively, which provides flexibility for selecting the best background for your map content. ```{code-cell} ipython3 m.add_basemap() ``` -### Add XYZ tile layer +### Adding XYZ Tile Layer -You can add XYZ tile layers to the map using the `add_tile_layer` method. +XYZ tile layers allow integration of specific tile services like topographic, satellite, or other thematic imagery from XYZ tile servers. By specifying the URL and parameters such as `opacity` and `visibility`, XYZ layers can be customized and styled to fit the needs of your map. ```{code-cell} ipython3 m = leafmap.Map() @@ -138,33 +272,85 @@ m.add_tile_layer(url, name="USGS TOpo", attribution="USGS", opacity=1.0, visible m ``` -### Add WMS layer +### Adding WMS Layer -You can add WMS layers to the map using the `add_wms_layer` method. +Web Map Service (WMS) layers provide access to external datasets served by web servers, such as thematic maps or detailed satellite imagery. Adding a WMS layer involves specifying the WMS URL and layer names, which allows for overlaying various data types such as natural imagery or land cover classifications. ```{code-cell} ipython3 -m = leafmap.Map(center=[-74.5447, 40.6892], zoom=8, style="streets") +m = leafmap.Map(center=[-74.5447, 40.6892], zoom=8, style="liberty") url = "https://img.nj.gov/imagerywms/Natural2015" layers = "Natural2015" m.add_wms_layer(url, layers=layers, before_id="aeroway_fill") +m.add_layer_control() m ``` ```{code-cell} ipython3 -m = leafmap.Map(center=[-100.307965, 46.98692], zoom=13, pitch=45, style="3d-hybrid") +m = leafmap.Map(center=[-100.307965, 46.98692], zoom=13, pitch=45, style="liberty") +m.add_basemap("Esri.WorldImagery") url = "https://fwspublicservices.wim.usgs.gov/wetlandsmapservice/services/Wetlands/MapServer/WMSServer" m.add_wms_layer(url, layers="1", name="NWI", opacity=0.6) -m.add_layer_control(bg_layers=True) +m.add_layer_control() m.add_legend(builtin_legend="NWI", title="Wetland Type") m ``` -### MapTiler styles +### Adding Raster Tiles + +Raster tiles provide a set of customized styles for map layers, such as watercolor or artistic styles, which can add unique visual elements. Configuring raster tile styles involves setting tile URLs, tile size, and attribution information. This setup provides access to a wide array of predefined designs, offering creative flexibility in how data is presented. + +With raster tiles, you can control zoom limits and apply unique visual IDs to distinguish between multiple raster sources on the map. + +```{code-cell} ipython3 +style = { + "version": 8, + "sources": { + "raster-tiles": { + "type": "raster", + "tiles": [ + "https://tiles.stadiamaps.com/tiles/stamen_watercolor/{z}/{x}/{y}.jpg" + ], + "tileSize": 256, + "attribution": "Map tiles by Stamen Design; Hosting by Stadia Maps. Data © OpenStreetMap contributors", + } + }, + "layers": [ + { + "id": "simple-tiles", + "type": "raster", + "source": "raster-tiles", + "minzoom": 0, + "maxzoom": 22, + } + ], +} +``` + +```{code-cell} ipython3 +m = leafmap.Map(center=[-74.5, 40], zoom=2, style=style) +m +``` + +## MapTiler + +To use MapTiler with this notebook, you need to set up a MapTiler API key. You can obtain a free API key by signing up at [https://cloud.maptiler.com/](https://cloud.maptiler.com/). + +```{code-cell} ipython3 +# import os +# os.environ["MAPTILER_KEY"] = "YOUR_API_KEY" +``` -You can use any named style from MapTiler by setting the style parameter to the name of the style. +Set the API key as an environment variable to access MapTiler's resources. Once set up, you can specify any named style from MapTiler by using the style parameter in the map setup. ![](https://i.imgur.com/dp2HxR2.png) +The following are examples of different styles available through MapTiler: + +- **Streets style**: This style displays detailed street information and is suited for urban data visualization. +- **Satellite style**: Provides high-resolution satellite imagery for various locations. +- **Hybrid style**: Combines satellite imagery with labels for a clear geographic context. +- **Topo style**: A topographic map showing terrain details, ideal for outdoor-related applications. + ```{code-cell} ipython3 m = leafmap.Map(style="streets") m @@ -185,47 +371,104 @@ m = leafmap.Map(style="topo") m ``` -## 3D mapping +### Add a vector tile source -### 3D terrain +To include vector data from MapTiler, first obtain the MapTiler API key and then set up a vector source with the desired tile data URL. The vector tile source can then be added to a layer to display features such as contour lines, which are styled for better visibility and engagement. -MapTiler provides a variety of basemaps and styles that can be used to create 3D maps. You can use any styles from the MapTiler basemap gallery and prefix the style name with `3d-`. For example, `3d-hybrid`, `3d-satellite`, or `3d-topo`. To use the hillshade only, you can use the `3d-hillshade` style. +```{code-cell} ipython3 +MAPTILER_KEY = leafmap.get_api_key("MAPTILER_KEY") +``` ```{code-cell} ipython3 -m = leafmap.Map(style="3d-hybrid") -m.add_layer_control(bg_layers=True) +m = leafmap.Map(center=[-122.447303, 37.753574], zoom=13, style="streets") +source = { + "type": "vector", + "url": f"https://api.maptiler.com/tiles/contours/tiles.json?key={MAPTILER_KEY}", +} +layer = { + "id": "terrain-data", + "type": "line", + "source": "contours", + "source-layer": "contour", + "layout": {"line-join": "round", "line-cap": "round"}, + "paint": {"line-color": "#ff69b4", "line-width": 1}, +} +m.add_source("contours", source) +m.add_layer(layer) m ``` +## 3D Mapping + +MapTiler provides a variety of 3D styles that enhance geographic data visualization. Styles can be prefixed with `3d-` to utilize 3D effects such as hybrid, satellite, and topo. The `3d-hillshade` style is used for visualizing hillshade effects alone. + +### 3D Terrain + +These examples demonstrate different ways to implement 3D terrain visualization: + +- **3D Hybrid style**: Adds terrain relief to urban data with hybrid visualization. +- **3D Satellite style**: Combines satellite imagery with 3D elevation, enhancing visual context for topography. +- **3D Topo style**: Provides a topographic view with elevation exaggeration and optional hillshade. +- **3D Terrain style**: Displays terrain with default settings for natural geographic areas. +- **3D Ocean style**: A specialized terrain style with oceanic details, using exaggeration and hillshade to emphasize depth. + +Each terrain map setup includes a pitch and bearing to adjust the map's angle and orientation, giving a better perspective of 3D features. + ```{code-cell} ipython3 -m = leafmap.Map(style="3d-satellite") +m = leafmap.Map( + center=[-122.1874314, 46.2022386], zoom=13, pitch=60, bearing=220, style="3d-hybrid" +) m.add_layer_control(bg_layers=True) m ``` ```{code-cell} ipython3 -m = leafmap.Map(style="3d-topo", exaggeration=1.5, hillshade=False) +m = leafmap.Map( + center=[-122.1874314, 46.2022386], + zoom=13, + pitch=60, + bearing=220, + style="3d-satellite", +) m.add_layer_control(bg_layers=True) m ``` ```{code-cell} ipython3 -m = leafmap.Map(style="3d-ocean", exaggeration=1.5, hillshade=True) +m = leafmap.Map( + center=[-122.1874314, 46.2022386], + zoom=13, + pitch=60, + bearing=220, + style="3d-topo", + exaggeration=1.5, + hillshade=False, +) m.add_layer_control(bg_layers=True) m ``` ```{code-cell} ipython3 m = leafmap.Map( - center=[-122.19861, 46.21168], zoom=13, pitch=60, bearing=150, style="3d-terrain" + center=[-122.1874314, 46.2022386], + zoom=13, + pitch=60, + bearing=220, + style="3d-terrain", ) m.add_layer_control(bg_layers=True) m ``` -### 3D buildings +```{code-cell} ipython3 +m = leafmap.Map(style="3d-ocean", exaggeration=1.5, hillshade=True) +m.add_layer_control(bg_layers=True) +m +``` + +### 3D Buildings -You can add 3D buildings to the map using the `add_3d_buildings` method. +Adding 3D buildings enhances urban visualizations, showing buildings with height variations. The setup involves specifying the MapTiler API key for vector tiles and adding building data as a 3D extrusion layer. The extrusion height and color can be set based on data attributes to visualize structures with varying heights, which can be useful in city planning and urban analysis. ```{code-cell} ipython3 m = leafmap.Map( @@ -289,9 +532,9 @@ m.add_layer_control() m ``` -### 3D indoor mapping +### 3D Indoor Mapping -Let's visualize indoor mapping data using the `add_geojson` method. +Indoor mapping data can be visualized by loading a GeoJSON file and applying the `add_geojson` method. This setup allows for displaying floorplans with attributes such as color, height, and opacity. It provides a realistic indoor perspective, which is useful for visualizing complex structures or navigating interior spaces. ```{code-cell} ipython3 data = "https://maplibre.org/maplibre-gl-js/docs/assets/indoor-3d-map.geojson" @@ -323,7 +566,15 @@ m.add_layer_control() m ``` -### 3D choropleth map +### 3D Choropleth Map + +Choropleth maps in 3D allow visualizing attribute data by height, where regions are colored and extruded based on specific attributes, such as age or population area. Two examples are provided below: + +- **European Countries (Age at First Marriage)**: The map displays different colors and extrusion heights based on age data. Color interpolations help represent data variations across regions, making it a suitable map for demographic studies. + +- **US Counties (Census Area)**: This example uses census data to display county areas in the United States, where each county’s area is represented with a different color and height based on its size. This type of map provides insights into geographic distribution and area proportions across the region. + +Both maps use a fill-extrusion style to dynamically adjust color and height, creating a 3D effect that enhances data interpretation. ```{code-cell} ipython3 m = leafmap.Map(center=[19.43, 49.49], zoom=3, pitch=60, style="basic") @@ -403,11 +654,21 @@ m.add_layer_control() m ``` -## Visualize vector data +## Visualize Vector Data + +Leafmap provides a variety of methods to visualize vector data on a map, allowing you to display points, lines, polygons, and other vector shapes with custom styling and interactivity. -Leafmap provides a variety of methods to visualize vector data on the map. +### Point Data -### Point data +The following examples demonstrate how to display points on the map. + +- **Simple Marker**: Initializes the map centered on a specific latitude and longitude, then adds a static marker to the location. + +- **Draggable Marker**: Similar to the simple marker, but with an additional option to make the marker draggable. This allows users to reposition it directly on the map. + +- **Multiple Points with GeoJSON**: Loads point data from a GeoJSON file containing world city locations. After reading the data, it’s added to the map as a layer named “cities.” Popups can be enabled to display additional information when a user clicks on a city. + +- **Custom Symbol Layer**: Loads point data as symbols instead of markers and customizes the symbol layout using icons, which can be scaled to any size. ```{code-cell} ipython3 m = leafmap.Map(center=[12.550343, 55.665957], zoom=8, style="positron") @@ -416,14 +677,16 @@ m ``` ```{code-cell} ipython3 -import requests +m = leafmap.Map(center=[12.550343, 55.665957], zoom=8, style="positron") +m.add_marker(lng_lat=[12.550343, 55.665957], options={"draggable": True}) +m ``` ```{code-cell} ipython3 url = ( "https://github.com/opengeos/datasets/releases/download/world/world_cities.geojson" ) -geojson = requests.get(url).json() +geojson = leafmap.read_geojson(url) ``` ```{code-cell} ipython3 @@ -452,7 +715,45 @@ m.add_popup("cities") m ``` -### Line data +### Customize Marker Icon Image + +To further customize point data, an image icon can be used instead of the default marker: + +- **Add Custom Icon**: Loads an OSGeo logo as the custom marker image. The GeoJSON source for conference locations is loaded, and each location is marked with the custom icon and labeled with the year. Layout options define the placement of text and icons. + +```{code-cell} ipython3 +m = leafmap.Map(center=[0, 0], zoom=1, style="positron") +image = "https://maplibre.org/maplibre-gl-js/docs/assets/osgeo-logo.png" +m.add_image("custom-marker", image) + +url = "https://github.com/opengeos/datasets/releases/download/places/osgeo_conferences.geojson" +geojson = leafmap.read_geojson(url) + +source = {"type": "geojson", "data": geojson} + +m.add_source("conferences", source) +layer = { + "id": "conferences", + "type": "symbol", + "source": "conferences", + "layout": { + "icon-image": "custom-marker", + "text-field": ["get", "year"], + "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"], + "text-offset": [0, 1.25], + "text-anchor": "top", + }, +} + +m.add_layer(layer) +m +``` + +### Line Data + +Lines can be displayed to represent routes, boundaries, or connections between locations: + +- **Basic Line**: Sets up a line with multiple coordinates to create a path. The map displays this path with rounded line joins and a defined color and width, giving it a polished appearance. ```{code-cell} ipython3 m = leafmap.Map(center=[-122.486052, 37.830348], zoom=15, style="streets") @@ -503,7 +804,15 @@ m.add_layer(layer) m ``` -### Polygon data +### Polygon Data + +Polygons represent regions or areas on the map. Leafmap offers options to display filled polygons with customizable colors and opacities. + +- **Basic Polygon**: Adds a GeoJSON polygon representing an area and customizes its fill color and opacity. + +- **Outlined Polygon**: In addition to filling the polygon, an outline color is specified to highlight the polygon’s boundary. Both fill and line layers are defined, enhancing visual clarity. + +- **Building Visualization with GeoJSON**: Uses a URL to load building data and displays it with a customized fill color and outline. The style uses a hybrid map view for additional context. ```{code-cell} ipython3 m = leafmap.Map(center=[-68.137343, 45.137451], zoom=5, style="streets") @@ -557,7 +866,30 @@ m.add_geojson(geojson, layer_type="fill", paint=paint) m ``` -### Multiple geometries +```{code-cell} ipython3 +m = leafmap.Map(style="hybrid") +geojson = "https://github.com/opengeos/datasets/releases/download/places/wa_overture_buildings.geojson" +paint = {"fill-color": "#ffff00", "fill-opacity": 0.5, "fill-outline-color": "#ff0000"} +m.add_geojson(geojson, layer_type="fill", paint=paint, name="Fill") +m +``` + +```{code-cell} ipython3 +m = leafmap.Map(style="hybrid") +geojson = "https://github.com/opengeos/datasets/releases/download/places/wa_overture_buildings.geojson" +paint_line = {"line-color": "#ff0000", "line-width": 3} +m.add_geojson(geojson, layer_type="line", paint=paint_line, name="Outline") +paint_fill = {"fill-color": "#ffff00", "fill-opacity": 0.5} +m.add_geojson(geojson, layer_type="fill", paint=paint_fill, name="Fill") +m.add_layer_control() +m +``` + +### Multiple Geometries + +This example displays both line and extrusion fills for complex data types: + +- **Extruded Blocks with Line Overlay**: Loads Vancouver building blocks data and applies both line and fill-extrusion styles. Each block’s height is based on an attribute, which provides a 3D effect. This is useful for visualizing value distribution across an urban landscape. ```{code-cell} ipython3 m = leafmap.Map( @@ -591,9 +923,9 @@ m m.layer_interact() ``` -### Marker cluster +### Marker Cluster -Create a marker cluster layer. +Clusters help manage large datasets, such as earthquake data, by grouping nearby markers. The color and size of clusters change based on the point count, and filters differentiate individual points from clusters. This example uses nested GeoJSON layers for visualizing clustered earthquake occurrences, with separate styles for individual points and clusters. ```{code-cell} ipython3 m = leafmap.Map(center=[-103.59179, 40.66995], zoom=3, style="streets") @@ -652,9 +984,15 @@ m.add_geojson( m ``` -### Local vector data +### Local Vector Data + +Local vector files, such as GeoJSON, can be loaded directly into the map. The example downloads a GeoJSON file representing U.S. states and adds it to the map using `open_geojson`. -You can load local vector data interactively using the `open_geojson` method. +```{code-cell} ipython3 +url = "https://github.com/opengeos/datasets/releases/download/us/us_states.geojson" +filepath = "data/us_states.geojson" +leafmap.download_file(url, filepath, quiet=True) +``` ```{code-cell} ipython3 m = leafmap.Map(center=[-100, 40], zoom=3) @@ -662,16 +1000,29 @@ m ``` ```{code-cell} ipython3 -url = "https://github.com/opengeos/datasets/releases/download/us/us_states.geojson" -filepath = "data/us_states.geojson" -leafmap.download_file(url, filepath, quiet=True) +m.open_geojson() ``` +### Local Vector Data + +Local vector files, such as GeoJSON, can be loaded directly into the map. The example downloads a GeoJSON file representing U.S. states and adds it to the map using `open_geojson`. + ```{code-cell} ipython3 -m.open_geojson() +m = leafmap.Map(center=[-100, 40], zoom=3, style="streets") +url = "https://github.com/opengeos/datasets/releases/download/us/us_states.geojson" +gdf = leafmap.geojson_to_gdf(url) +paint = { + "fill-color": "#3388ff", + "fill-opacity": 0.8, + "fill-outline-color": "#ffffff", +} +m.add_gdf(gdf, layer_type="fill", name="States", paint=paint) +m ``` -### Change building color +### Change Building Color + +You can customize the color and opacity of buildings based on the map’s zoom level. This example changes building colors from orange at lower zoom levels to lighter shades as the zoom level increases. Additionally, the opacity gradually transitions to fully opaque, making buildings more visible at close-up zoom levels. ```{code-cell} ipython3 m = leafmap.Map(center=[-90.73414, 14.55524], zoom=13, style="basic") @@ -685,6 +1036,7 @@ m.set_paint_property( "fill-opacity", ["interpolate", ["exponential", 0.5], ["zoom"], 15, 0, 22, 1], ) +m.add_layer_control(bg_layers=True) m ``` @@ -692,123 +1044,197 @@ m m.add_call("zoomTo", 19, {"duration": 9000}) ``` -### Live feature update +### Add a New Layer Below Labels -#### Animate a point along a route +A layer can be added below existing labels on the map to enhance clarity without obscuring labels. The urban areas dataset is displayed as a fill layer in a color and opacity that visually distinguishes it from other map elements. The layer is positioned below symbols, allowing place names to remain visible. ```{code-cell} ipython3 -import time -``` - -```{code-cell} ipython3 -m = leafmap.Map(center=[-100, 40], zoom=3, style="streets") -url = "https://github.com/opengeos/datasets/releases/download/us/arc_with_bearings.geojson" -geojson = requests.get(url).json() -bearings = geojson["features"][0]["properties"]["bearings"] -coordinates = geojson["features"][0]["geometry"]["coordinates"][:-1] -m.add_geojson(geojson, name="route") - -origin = [-122.414, 37.776] -destination = [-77.032, 38.913] - -point = { - "type": "FeatureCollection", - "features": [ - { - "type": "Feature", - "properties": {}, - "geometry": {"type": "Point", "coordinates": origin}, - } - ], +m = leafmap.Map(center=[-88.137343, 35.137451], zoom=4, style="streets") +source = { + "type": "geojson", + "data": "https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_50m_urban_areas.geojson", } -source = {"type": "geojson", "data": point} -m.add_source("point", source) +m.add_source("urban-areas", source) +first_symbol_layer = m.find_first_symbol_layer() layer = { - "id": "point", - "source": "point", - "type": "symbol", - "layout": { - "icon-image": "airport_15", - "icon-rotate": ["get", "bearing"], - "icon-rotation-alignment": "map", - "icon-overlap": "always", - "icon-ignore-placement": True, - }, + "id": "urban-areas-fill", + "type": "fill", + "source": "urban-areas", + "layout": {}, + "paint": {"fill-color": "#f08", "fill-opacity": 0.4}, } -m.add_layer(layer) +m.add_layer(layer, before_id=first_symbol_layer["id"]) m ``` -```{code-cell} ipython3 -for index, coordinate in enumerate(coordinates): - point["features"][0]["geometry"]["coordinates"] = coordinate - point["features"][0]["properties"]["bearing"] = bearings[index] - m.set_data("point", point) - time.sleep(0.05) -``` +### Heat Map -#### Update a feature in realtime +Heatmaps visually represent data density. This example uses earthquake data and configures the heatmap layer with dynamic properties, such as weight, intensity, color, and radius, based on earthquake magnitudes. Circles are added to indicate individual earthquakes, with colors and sizes varying according to their magnitude. ```{code-cell} ipython3 -m = leafmap.Map(center=[-122.019807, 45.632433], zoom=14, pitch=60, style="3d-terrain") +m = leafmap.Map(center=[-120, 50], zoom=2, style="basic") +source = { + "type": "geojson", + "data": "https://maplibre.org/maplibre-gl-js/docs/assets/earthquakes.geojson", +} +m.add_source("earthquakes", source) +layer = { + "id": "earthquakes-heat", + "type": "heatmap", + "source": "earthquakes", + "maxzoom": 9, + "paint": { + # Increase the heatmap weight based on frequency and property magnitude + "heatmap-weight": ["interpolate", ["linear"], ["get", "mag"], 0, 0, 6, 1], + # Increase the heatmap color weight weight by zoom level + # heatmap-intensity is a multiplier on top of heatmap-weight + "heatmap-intensity": ["interpolate", ["linear"], ["zoom"], 0, 1, 9, 3], + # Color ramp for heatmap. Domain is 0 (low) to 1 (high). + # Begin color ramp at 0-stop with a 0-transparency color + # to create a blur-like effect. + "heatmap-color": [ + "interpolate", + ["linear"], + ["heatmap-density"], + 0, + "rgba(33,102,172,0)", + 0.2, + "rgb(103,169,207)", + 0.4, + "rgb(209,229,240)", + 0.6, + "rgb(253,219,199)", + 0.8, + "rgb(239,138,98)", + 1, + "rgb(178,24,43)", + ], + # Adjust the heatmap radius by zoom level + "heatmap-radius": ["interpolate", ["linear"], ["zoom"], 0, 2, 9, 20], + # Transition from heatmap to circle layer by zoom level + "heatmap-opacity": ["interpolate", ["linear"], ["zoom"], 7, 1, 9, 0], + }, +} +m.add_layer(layer, before_id="waterway") +layer2 = { + "id": "earthquakes-point", + "type": "circle", + "source": "earthquakes", + "minzoom": 7, + "paint": { + # Size circle radius by earthquake magnitude and zoom level + "circle-radius": [ + "interpolate", + ["linear"], + ["zoom"], + 7, + ["interpolate", ["linear"], ["get", "mag"], 1, 1, 6, 4], + 16, + ["interpolate", ["linear"], ["get", "mag"], 1, 5, 6, 50], + ], + # Color circle by earthquake magnitude + "circle-color": [ + "interpolate", + ["linear"], + ["get", "mag"], + 1, + "rgba(33,102,172,0)", + 2, + "rgb(103,169,207)", + 3, + "rgb(209,229,240)", + 4, + "rgb(253,219,199)", + 5, + "rgb(239,138,98)", + 6, + "rgb(178,24,43)", + ], + "circle-stroke-color": "white", + "circle-stroke-width": 1, + # Transition from heatmap to circle layer by zoom level + "circle-opacity": ["interpolate", ["linear"], ["zoom"], 7, 0, 8, 1], + }, +} +m.add_layer(layer2, before_id="waterway") m ``` -```{code-cell} ipython3 -import geopandas as gpd -``` +### Visualize Population Density -```{code-cell} ipython3 -url = "https://maplibre.org/maplibre-gl-js/docs/assets/hike.geojson" -gdf = gpd.read_file(url) -coordinates = list(gdf.geometry[0].coords) -print(coordinates[:5]) -``` +Population density can be calculated and displayed dynamically. This example loads a GeoJSON of Rwandan provinces, calculating density by dividing population by area. The fill color of each province is then adjusted based on density, with different color schemes applied depending on the zoom level. ```{code-cell} ipython3 +m = leafmap.Map(center=[30.0222, -1.9596], zoom=7, style="streets") source = { "type": "geojson", - "data": { - "type": "Feature", - "geometry": {"type": "LineString", "coordinates": [coordinates[0]]}, - }, + "data": "https://maplibre.org/maplibre-gl-js/docs/assets/rwanda-provinces.geojson", } -m.add_source("trace", source) +m.add_source("rwanda-provinces", source) layer = { - "id": "trace", - "type": "line", - "source": "trace", - "paint": {"line-color": "yellow", "line-opacity": 0.75, "line-width": 5}, + "id": "rwanda-provinces", + "type": "fill", + "source": "rwanda-provinces", + "layout": {}, + "paint": { + "fill-color": [ + "let", + "density", + ["/", ["get", "population"], ["get", "sq-km"]], + [ + "interpolate", + ["linear"], + ["zoom"], + 8, + [ + "interpolate", + ["linear"], + ["var", "density"], + 274, + ["to-color", "#edf8e9"], + 1551, + ["to-color", "#006d2c"], + ], + 10, + [ + "interpolate", + ["linear"], + ["var", "density"], + 274, + ["to-color", "#eff3ff"], + 1551, + ["to-color", "#08519c"], + ], + ], + ], + "fill-opacity": 0.7, + }, } m.add_layer(layer) -m.jump_to({"center": coordinates[0], "zoom": 14}) -m.set_pitch(30) +m ``` -```{code-cell} ipython3 -for coord in coordinates: - time.sleep(0.005) - source["data"]["geometry"]["coordinates"].append(coord) - m.set_data("trace", source["data"]) - m.pan_to(coord) -``` +## Visualize Raster Data -## Visualize raster data +### Local Raster Data -### Local raster data +To visualize local raster files, use the `add_raster` method. In the example, a Landsat image is downloaded and displayed using two different band combinations: -You can load local raster data using the `add_raster` method. +- **Band Combination 3-2-1 (True Color)**: Simulates natural colors in the RGB channels. +- **Band Combination 4-3-2**: Enhances vegetation, displaying it in red for better visual contrast. +These layers are added to the map along with controls to toggle them. You can adjust brightness and contrast with the `vmin` and `vmax` arguments to improve clarity. ```{code-cell} ipython3 url = "https://github.com/opengeos/datasets/releases/download/raster/landsat.tif" filepath = "landsat.tif" -leafmap.download_file(url, filepath) +leafmap.download_file(url, filepath, quiet=True) ``` ```{code-cell} ipython3 m = leafmap.Map(style="streets") m.add_raster(filepath, indexes=[3, 2, 1], vmin=0, vmax=100, name="Landsat-321") m.add_raster(filepath, indexes=[4, 3, 2], vmin=0, vmax=100, name="Landsat-432") +m.add_layer_control() m ``` @@ -819,7 +1245,7 @@ m.layer_interact() ```{code-cell} ipython3 url = "https://github.com/opengeos/datasets/releases/download/raster/srtm90.tif" filepath = "srtm90.tif" -leafmap.download_file(url, filepath) +leafmap.download_file(url, filepath, quiet=True) ``` ```{code-cell} ipython3 @@ -828,13 +1254,15 @@ m.add_raster(filepath, colormap="terrain", name="DEM") m ``` +A Digital Elevation Model (DEM) is also downloaded and visualized with a terrain color scheme. Leafmap’s `layer_interact` method allows interactive adjustments. + ```{code-cell} ipython3 m.layer_interact() ``` ### Cloud Optimized GeoTIFF (COG) -You can load Cloud Optimized GeoTIFF (COG) data using the `add_cog_layer` method. +Cloud Optimized GeoTIFFs (COG) are large raster files stored on cloud platforms, allowing efficient streaming and loading. This example loads satellite imagery of Libya before and after an event, showing the change over time. Each image is loaded with `add_cog_layer`, and layers can be toggled for comparison. Using `fit_bounds`, the map centers on the COG layer to fit its boundaries. ```{code-cell} ipython3 m = leafmap.Map(style="satellite") @@ -846,6 +1274,7 @@ after = ( ) m.add_cog_layer(before, name="Before", attribution="Maxar") m.add_cog_layer(after, name="After", attribution="Maxar", fit_bounds=True) +m.add_layer_control() m ``` @@ -853,323 +1282,402 @@ m m.layer_interact() ``` -### STAC layer +### STAC Layer -You can load SpatioTemporal Asset Catalog (STAC) data using the `add_stac_layer` method. +The SpatioTemporal Asset Catalog (STAC) standard organizes large satellite data collections. With `add_stac_layer`, this example loads Canadian satellite data, displaying both a panchromatic and an RGB layer from the same source. This approach allows easy switching between views. ```{code-cell} ipython3 -m = leafmap.Map() +m = leafmap.Map(style="streets") url = "https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json" -m.add_stac_layer(url, bands=["B4", "B3", "B2"], name="SPOT", vmin=0, vmax=150, nodata=0) +m.add_stac_layer(url, bands=["pan"], name="Panchromatic", vmin=0, vmax=150) +m.add_stac_layer(url, bands=["B4", "B3", "B2"], name="RGB", vmin=0, vmax=150) +m.add_layer_control() m ``` -## Customize layer styles +```{code-cell} ipython3 +m.layer_interact() +``` -+++ +For more control, the `collection` and `item` parameters let you specify specific assets, such as color infrared bands, for focused analysis. -### Change layer color +```{code-cell} ipython3 +collection = "landsat-8-c2-l2" +item = "LC08_L2SP_047027_20201204_02_T1" +``` ```{code-cell} ipython3 -m = leafmap.Map(center=[12.338, 45.4385], zoom=17, style="streets") -m +leafmap.stac_assets(collection=collection, item=item, titiler_endpoint="pc") ``` ```{code-cell} ipython3 -m.style_layer_interact(id="water") +m = leafmap.Map(style="satellite") +m.add_stac_layer( + collection=collection, + item=item, + assets=["SR_B5", "SR_B4", "SR_B3"], + name="Color infrared", +) +m ``` -### Change case of labels +## Interact with the Map + +Interactivity allows for a more tailored map experience. + + +### Display a Non-Interactive Map + +To create a static map, set `interactive=False`. This disables all user interactions, making it ideal for static presentations. ```{code-cell} ipython3 -m = leafmap.Map(center=[-116.231, 43.604], zoom=11, style="streets") -geojson = { - "type": "geojson", - "data": "https://maplibre.org/maplibre-gl-js/docs/assets/boise.geojson", -} -m.add_source("off-leash-areas", geojson) -layer = { - "id": "off-leash-areas", - "type": "symbol", - "source": "off-leash-areas", - "layout": { - "icon-image": "dog-park-11", - "text-field": [ - "format", - ["upcase", ["get", "FacilityName"]], - {"font-scale": 0.8}, - "\n", - {}, - ["downcase", ["get", "Comments"]], - {"font-scale": 0.6}, - ], - "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"], - "text-offset": [0, 0.6], - "text-anchor": "top", - }, -} -m.add_layer(layer) +m = leafmap.Map( + center=[-122.65, 45.52], zoom=9, interactive=False, style="liberty", controls={} +) m ``` -```{code-cell} ipython3 +### Disable Scroll Zoom + +Use `scroll_zoom=False` to prevent map zooming with the scroll wheel, maintaining a fixed zoom level. +```{code-cell} ipython3 +m = leafmap.Map(center=[-122.65, 45.52], zoom=9, scroll_zoom=False, style="liberty") +m ``` -## PMTiles +### Fit Bounds -Leafmap supports the [PMTiles](https://protomaps.com/docs/pmtiles/) format for fast and efficient rendering of vector tiles. +The `fit_bounds` method focuses the map on a specified area. In this example, the map centers on Kenya. Additionally, a GeoJSON line is added to the map, and its bounds are automatically calculated with `geojson_bounds` for a custom zoom fit. -### Protomaps sample data +```{code-cell} ipython3 +m = leafmap.Map(center=[-74.5, 40], zoom=9, style="liberty") +m +``` + +Fit to Kenya. ```{code-cell} ipython3 -url = "https://open.gishub.org/data/pmtiles/protomaps_firenze.pmtiles" -metadata = leafmap.pmtiles_metadata(url) -print(f"layer names: {metadata['layer_names']}") -print(f"bounds: {metadata['bounds']}") +bounds = [[32.958984, -5.353521], [43.50585, 5.615985]] +m.fit_bounds(bounds) ``` ```{code-cell} ipython3 -m = leafmap.Map() +m = leafmap.Map(center=[-77.0214, 38.897], zoom=12, style="liberty") -style = { - "version": 8, - "sources": { - "example_source": { - "type": "vector", - "url": "pmtiles://" + url, - "attribution": "PMTiles", - } - }, - "layers": [ - { - "id": "buildings", - "source": "example_source", - "source-layer": "landuse", - "type": "fill", - "paint": {"fill-color": "steelblue"}, - }, +geojson = { + "type": "FeatureCollection", + "features": [ { - "id": "roads", - "source": "example_source", - "source-layer": "roads", - "type": "line", - "paint": {"line-color": "black"}, - }, + "type": "Feature", + "geometry": { + "type": "LineString", + "properties": {}, + "coordinates": [ + [-77.0366048812866, 38.89873175227713], + [-77.03364372253417, 38.89876515143842], + [-77.03364372253417, 38.89549195896866], + [-77.02982425689697, 38.89549195896866], + [-77.02400922775269, 38.89387200688839], + [-77.01519012451172, 38.891416957534204], + [-77.01521158218382, 38.892068305429156], + [-77.00813055038452, 38.892051604275686], + [-77.00832366943358, 38.89143365883688], + [-77.00818419456482, 38.89082405874451], + [-77.00815200805664, 38.88989712255097], + ], + }, + } ], } -# style = leafmap.pmtiles_style(url) # Use default style - -m.add_pmtiles( - url, - style=style, - visible=True, - opacity=1.0, - tooltip=True, -) +m.add_source("LineString", {"type": "geojson", "data": geojson}) +layer = { + "id": "LineString", + "type": "line", + "source": "LineString", + "layout": {"line-join": "round", "line-cap": "round"}, + "paint": {"line-color": "#BF93E4", "line-width": 5}, +} +m.add_layer(layer) m ``` ```{code-cell} ipython3 -m.layer_interact() +bounds = leafmap.geojson_bounds(geojson) +bounds ``` -### Overture data - -You can also visualize Overture data. Inspired by [overture-maps](https://github.com/tebben/overture-maps). - -+++ +```{code-cell} ipython3 +m.fit_bounds(bounds) +``` -### Source Cooperative +### Restrict Map Panning to an Area -Let's visualize the [Google-Microsoft Open Buildings - combined by VIDA](https://beta.source.coop/repositories/vida/google-microsoft-open-buildings/description). +To limit map panning to a specific area, define a bounding box. The map is then restricted within the bounds, ensuring users do not accidentally pan away from the area of interest. ```{code-cell} ipython3 -url = "https://data.source.coop/vida/google-microsoft-open-buildings/pmtiles/go_ms_building_footprints.pmtiles" -metadata = leafmap.pmtiles_metadata(url) -print(f"layer names: {metadata['layer_names']}") -print(f"bounds: {metadata['bounds']}") +bounds = [ + [-74.04728500751165, 40.68392799015035], + [-73.91058699000139, 40.87764500765852], +] ``` ```{code-cell} ipython3 -m = leafmap.Map(center=[0, 20], zoom=2, height="800px") -m.add_basemap("Google Hybrid", visible=False) +m = leafmap.Map(center=[-73.9978, 40.7209], zoom=13, max_bounds=bounds, style="liberty") +m +``` -style = { - "version": 8, - "sources": { - "example_source": { - "type": "vector", - "url": "pmtiles://" + url, - "attribution": "PMTiles", - } - }, - "layers": [ - { - "id": "buildings", - "source": "example_source", - "source-layer": "building_footprints", - "type": "fill", - "paint": {"fill-color": "#3388ff", "fill-opacity": 0.5}, - }, - ], -} +### Fly To -# style = leafmap.pmtiles_style(url) # Use default style +The `fly_to` method smoothly navigates to specified coordinates. Parameters like speed and zoom provide control over the fly-to effect. This example flies from the initial map location to New York City. -m.add_pmtiles( - url, - style=style, - visible=True, - opacity=1.0, - tooltip=True, -) +```{code-cell} ipython3 +m = leafmap.Map(center=[-2.242467, 53.478122], zoom=9, style="liberty") m ``` ```{code-cell} ipython3 -m.layer_interact() +m.fly_to(lon=-73.983609, lat=40.754368, zoom=12) ``` -### 3D PMTiles +```{code-cell} ipython3 +m = leafmap.Map(center=[-74.5, 40], zoom=9, style="liberty") +m +``` -Visualize the global building data in 3D. +```{code-cell} ipython3 +options = { + "lon": 74.5, + "lat": 40, + "zoom": 9, + "bearing": 0, + "speed": 0.2, + "curve": 1, + "essential": True, +} + +m.fly_to(**options) +``` + +### Jump to a Series of Locations + +Using `jump_to`, you can navigate between multiple locations. This example sets up a list of coordinates representing cities and automatically pans to each one in sequence. Adding a delay between transitions enhances the animation effect. ```{code-cell} ipython3 -url = "https://data.source.coop/cholmes/overture/overture-buildings.pmtiles" -metadata = leafmap.pmtiles_metadata(url) -print(f"layer names: {metadata['layer_names']}") -print(f"bounds: {metadata['bounds']}") +import time ``` ```{code-cell} ipython3 -m = leafmap.Map( - center=[-74.0095, 40.7046], zoom=16, pitch=60, bearing=-17, style="positron" -) -m.add_basemap("OpenStreetMap.Mapnik") -m.add_basemap("Esri.WorldImagery", visible=False) +m = leafmap.Map(center=[100.507, 13.745], zoom=9, style="streets") -style = { - "layers": [ +cities = { + "type": "FeatureCollection", + "features": [ { - "id": "buildings", - "source": "example_source", - "source-layer": "buildings", - "type": "fill-extrusion", - "filter": [ - ">", - ["get", "height"], - 0, - ], # only show buildings with height info - "paint": { - "fill-extrusion-color": [ - "interpolate", - ["linear"], - ["get", "height"], - 0, - "lightgray", - 200, - "royalblue", - 400, - "lightblue", - ], - "fill-extrusion-height": ["*", ["get", "height"], 1], - }, + "type": "Feature", + "properties": {}, + "geometry": {"type": "Point", "coordinates": [100.507, 13.745]}, + }, + { + "type": "Feature", + "properties": {}, + "geometry": {"type": "Point", "coordinates": [98.993, 18.793]}, + }, + { + "type": "Feature", + "properties": {}, + "geometry": {"type": "Point", "coordinates": [99.838, 19.924]}, + }, + { + "type": "Feature", + "properties": {}, + "geometry": {"type": "Point", "coordinates": [102.812, 17.408]}, + }, + { + "type": "Feature", + "properties": {}, + "geometry": {"type": "Point", "coordinates": [100.458, 7.001]}, + }, + { + "type": "Feature", + "properties": {}, + "geometry": {"type": "Point", "coordinates": [100.905, 12.935]}, }, ], } - -m.add_pmtiles( - url, - style=style, - visible=True, - opacity=1.0, - tooltip=True, - template="Height: {{height}}
Country: {{country_iso}}", - fit_bounds=False, -) -m.add_layer_control() m ``` -### 3D buildings - ```{code-cell} ipython3 -m = leafmap.Map( - center=[-74.0095, 40.7046], zoom=16, pitch=60, bearing=-17, style="positron" -) -m.add_basemap("Esri.WorldImagery", visible=False) -m.add_overture_3d_buildings(release="2024-09-18", template="simple") -m.add_layer_control() -m +for index, city in enumerate(cities["features"]): + time.sleep(2) + coords = city["geometry"]["coordinates"] + m.jump_to({"center": coords}) ``` -### 2D buildings +### Get Coordinates of the Mouse Pointer + +With widgets, you can display the current mouse pointer coordinates as it moves across the map. This is useful for precision mapping tasks where knowing exact coordinates is essential. ```{code-cell} ipython3 -m = leafmap.Map(center=[-74.0095, 40.7046], zoom=16) -m.add_basemap("Esri.WorldImagery", visible=False) -m.add_overture_data(theme="buildings", opacity=0.8) -m.add_layer_control() +import ipywidgets as widgets +``` + +```{code-cell} ipython3 +m = leafmap.Map(center=[-74.5, 40], zoom=9, style="streets") m ``` -### Transportation +```{code-cell} ipython3 +m.clicked +``` ```{code-cell} ipython3 -m = leafmap.Map(center=[-74.0095, 40.7046], zoom=16) -m.add_basemap("Esri.WorldImagery", visible=False) -m.add_overture_data(theme="transportation", opacity=0.8) -m.add_layer_control() -m +output = widgets.Output() + + +def log_lng_lat(lng_lat): + with output: + output.clear_output() + print(lng_lat.new) + + +m.observe(log_lng_lat, names="clicked") +output ``` -### Places +## Customizing Layer Styles + +Customizing layer styles enables personalized map designs. + +### Change Layer Color + +Use `style_layer_interact` to interactively change the color of map layers, such as water bodies. This method provides an interactive palette for immediate style changes. ```{code-cell} ipython3 -m = leafmap.Map(center=[-74.0095, 40.7046], zoom=16) -m.add_basemap("Esri.WorldImagery", visible=False) -m.add_overture_data(theme="places", opacity=0.8) -m.add_layer_control() +m = leafmap.Map(center=[12.338, 45.4385], zoom=17, style="streets") m ``` -### Addresses +```{code-cell} ipython3 +m.style_layer_interact(id="water") +``` + +### Change Case of Labels + +This example displays labels in upper or lower case based on their properties. The layout options let you customize font, size, and alignment. For example, facility names are displayed in uppercase, and comments are displayed in lowercase for contrast. ```{code-cell} ipython3 -m = leafmap.Map(center=[-74.0095, 40.7046], zoom=16) -m.add_basemap("Esri.WorldImagery", visible=False) -m.add_overture_data(theme="addresses", opacity=0.8) -m.add_layer_control() +m = leafmap.Map(center=[-116.231, 43.604], zoom=11, style="streets") +geojson = { + "type": "geojson", + "data": "https://maplibre.org/maplibre-gl-js/docs/assets/boise.geojson", +} +m.add_source("off-leash-areas", geojson) +layer = { + "id": "off-leash-areas", + "type": "symbol", + "source": "off-leash-areas", + "layout": { + "icon-image": "dog-park-11", + "text-field": [ + "format", + ["upcase", ["get", "FacilityName"]], + {"font-scale": 0.8}, + "\n", + {}, + ["downcase", ["get", "Comments"]], + {"font-scale": 0.6}, + ], + "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"], + "text-offset": [0, 0.6], + "text-anchor": "top", + }, +} +m.add_layer(layer) m ``` -### Base +### Variable Label Placement + +Labels can be automatically positioned around features with `text-variable-anchor`. This example defines multiple anchor points for labels to avoid overlap and ensure clear visibility. The radial offset and auto-justification properties create a professional, clutter-free appearance around points of interest. ```{code-cell} ipython3 -m = leafmap.Map(center=[-74.0095, 40.7046], zoom=16) -m.add_basemap("Esri.WorldImagery", visible=False) -m.add_overture_data(theme="base", opacity=0.8) -m.add_layer_control() +m = leafmap.Map(center=[-77.04, 38.907], zoom=11, style="streets") + +places = { + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": {"description": "Ford's Theater", "icon": "theatre"}, + "geometry": {"type": "Point", "coordinates": [-77.038659, 38.931567]}, + }, + { + "type": "Feature", + "properties": {"description": "The Gaslight", "icon": "theatre"}, + "geometry": {"type": "Point", "coordinates": [-77.003168, 38.894651]}, + }, + { + "type": "Feature", + "properties": {"description": "Horrible Harry's", "icon": "bar"}, + "geometry": {"type": "Point", "coordinates": [-77.090372, 38.881189]}, + }, + { + "type": "Feature", + "properties": {"description": "Bike Party", "icon": "bicycle"}, + "geometry": {"type": "Point", "coordinates": [-77.052477, 38.943951]}, + }, + { + "type": "Feature", + "properties": {"description": "Rockabilly Rockstars", "icon": "music"}, + "geometry": {"type": "Point", "coordinates": [-77.031706, 38.914581]}, + }, + { + "type": "Feature", + "properties": {"description": "District Drum Tribe", "icon": "music"}, + "geometry": {"type": "Point", "coordinates": [-77.020945, 38.878241]}, + }, + { + "type": "Feature", + "properties": {"description": "Motown Memories", "icon": "music"}, + "geometry": {"type": "Point", "coordinates": [-77.007481, 38.876516]}, + }, + ], +} +source = {"type": "geojson", "data": places} +m.add_source("places", source) + +layer = { + "id": "poi-labels", + "type": "symbol", + "source": "places", + "layout": { + "text-field": ["get", "description"], + "text-variable-anchor": ["top", "bottom", "left", "right"], + "text-radial-offset": 0.5, + "text-justify": "auto", + "icon-image": ["concat", ["get", "icon"], "_15"], + }, +} +m.add_layer(layer) m ``` -### Divisions - ```{code-cell} ipython3 -m = leafmap.Map() -m.add_basemap("Esri.WorldImagery", visible=False) -m.add_overture_data(theme="divisions", opacity=0.8) -m.add_layer_control() -m +m.rotate_to(bearing=180, options={"duration": 10000}) ``` -## Add custom components +## Adding Custom Components -You can add custom components to the map, including images, videos, text, color bar, and legend. +Enhance your maps by adding custom components such as images, videos, text, color bars, and legends. -### Add image +### Add Image + +You can add an image as an overlay or as an icon for a specific layer. For instance: +- Overlaying an image directly on the map at the "bottom-right" corner. +- Adding an icon image to a feature. In the example, a "cat" image is loaded, and a marker is added at coordinates `[0, 0]` with a label "I love kitty!" above the icon. ```{code-cell} ipython3 m = leafmap.Map(center=[0.349419, -1.80921], zoom=3, style="streets") @@ -1217,9 +1725,7 @@ m.add_html(content, bg_color="transparent", position="bottom-right") m ``` -```{code-cell} ipython3 - -``` +To customize icons, you can also generate icon data with `numpy`, creating unique color gradients and using it as a map icon. ```{code-cell} ipython3 import numpy as np @@ -1248,7 +1754,7 @@ image_dict = { "data": flat_data.tolist(), } -m = leafmap.Map(center=[0, 0], zoom=1, style="streets") +m = leafmap.Map(center=[0, 0], zoom=1, style="liberty") m.add_image("gradient", image_dict) source = { "type": "geojson", @@ -1272,14 +1778,14 @@ m.add_layer(layer) m ``` -```{code-cell} ipython3 - -``` +### Add Text -### Add text +Add text annotations to the map, specifying parameters like font size and background color. For example: +- Text "Hello World" in the bottom-right corner with a transparent background. +- "Awesome Text!" in the top-left corner with a slightly opaque white background, making it stand out. ```{code-cell} ipython3 -m = leafmap.Map(center=[-100, 40], zoom=3, style="streets") +m = leafmap.Map(center=[-100, 40], zoom=3, style="liberty") text = "Hello World" m.add_text(text, fontsize=20, position="bottom-right") text2 = "Awesome Text!" @@ -1289,6 +1795,8 @@ m ### Add GIF +GIFs can be added as animated overlays to bring your map to life. Example: add a sloth GIF in the bottom-right and a second GIF in the bottom-left corner, with a text label indicating “I love sloth!” for added character. + ```{code-cell} ipython3 m = leafmap.Map(center=[-100, 40], zoom=3, style="positron") image = "https://i.imgur.com/KeiAsTv.gif" @@ -1302,6 +1810,8 @@ m ### Add HTML +Embed custom HTML content to display various HTML elements, such as emojis or stylized text. You can also adjust the font size and background transparency for better integration into the map design. + ```{code-cell} ipython3 m = leafmap.Map(center=[-100, 40], zoom=3, style="positron") html = """ @@ -1324,42 +1834,44 @@ m.add_html(html, bg_color="transparent") m ``` -### Add colorbar +### Add Colorbar -```{code-cell} ipython3 -dem = "https://github.com/opengeos/datasets/releases/download/raster/srtm90.tif" -``` +Adding a color bar enhances data interpretation. In the example: +1. A Digital Elevation Model (DEM) is displayed with a color ramp from 0 to 1500 meters. +2. `add_colorbar` method is used to create a color bar with labels, adjusting its position, opacity, and orientation for optimal readability. ```{code-cell} ipython3 -m = leafmap.Map(style="streets") +m = leafmap.Map(style="topo") +dem = "https://github.com/opengeos/datasets/releases/download/raster/dem.tif" m.add_cog_layer( dem, name="DEM", colormap_name="terrain", - rescale="0, 4000", + rescale="0, 1500", fit_bounds=True, - nodata=0, + nodata=np.nan, ) m.add_colorbar( - cmap="terrain", vmin=0, vmax=4000, label="Elevation (m)", position="bottom-right" + cmap="terrain", vmin=0, vmax=1500, label="Elevation (m)", position="bottom-right" ) +m.add_layer_control() m ``` ```{code-cell} ipython3 -m = leafmap.Map(style="streets") +m = leafmap.Map(style="topo") m.add_cog_layer( dem, name="DEM", colormap_name="terrain", - rescale="0, 4000", - nodata=0, + rescale="0, 1500", + nodata=np.nan, fit_bounds=True, ) m.add_colorbar( cmap="terrain", vmin=0, - vmax=4000, + vmax=1500, label="Elevation (m)", position="bottom-right", transparent=True, @@ -1368,19 +1880,19 @@ m ``` ```{code-cell} ipython3 -m = leafmap.Map(style="streets") +m = leafmap.Map(style="topo") m.add_cog_layer( dem, name="DEM", colormap_name="terrain", - rescale="0, 4000", - nodata=0, + rescale="0, 1500", + nodata=np.nan, fit_bounds=True, ) m.add_colorbar( cmap="terrain", vmin=0, - vmax=4000, + vmax=1500, label="Elevation (m)", position="bottom-right", width=0.2, @@ -1390,7 +1902,11 @@ m.add_colorbar( m ``` -### Add legend +### Add Legend + +Custom legends help users understand data classifications. Two methods are shown: +1. Using built-in legends, such as for NLCD (National Land Cover Database) or wetland types. +2. Custom legends are built with a dictionary of land cover types and colors. This legend provides descriptive color-coding for various land cover types, with configurable background opacity to blend with the map. ```{code-cell} ipython3 m = leafmap.Map(center=[-100, 40], zoom=3, style="positron") @@ -1455,52 +1971,310 @@ m.add_legend( m ``` -### Add video +### Add Video + +Videos can be added with geographic context by specifying corner coordinates. Videos must be listed in multiple formats to ensure compatibility across browsers. The coordinates array should define the video’s location on the map in the order: top-left, top-right, bottom-right, and bottom-left. This is demonstrated by adding drone footage to a satellite map view, enhancing the user experience with real-world visuals. + + +The `urls` value is an array. For each URL in the array, a video element source will be created. To support the video across browsers, supply URLs in multiple formats. +The `coordinates` array contains [longitude, latitude] pairs for the video corners listed in clockwise order: top left, top right, bottom right, bottom left. + +```{code-cell} ipython3 +m = leafmap.Map( + center=[-122.514426, 37.562984], zoom=17, bearing=-96, style="satellite" +) +urls = [ + "https://static-assets.mapbox.com/mapbox-gl-js/drone.mp4", + "https://static-assets.mapbox.com/mapbox-gl-js/drone.webm", +] +coordinates = [ + [-122.51596391201019, 37.56238816766053], + [-122.51467645168304, 37.56410183312965], + [-122.51309394836426, 37.563391708549425], + [-122.51423120498657, 37.56161849366671], +] +m.add_video(urls, coordinates) +m.add_layer_control() +m +``` + +```{code-cell} ipython3 +m = leafmap.Map(center=[-115, 25], zoom=4, style="satellite") +urls = [ + "https://data.opengeos.org/patricia_nasa.mp4", + "https://data.opengeos.org/patricia_nasa.webm", +] +coordinates = [ + [-130, 32], + [-100, 32], + [-100, 13], + [-130, 13], +] +m.add_video(urls, coordinates) +m.add_layer_control() +m +``` + +## PMTiles + +Leafmap supports the [PMTiles](https://protomaps.com/docs/pmtiles/) format, enabling efficient storage and fast rendering of vector tiles directly in the browser. + +### Protomaps Sample Data + +Load Protomaps data in PMTiles format for fast, high-resolution vector map data rendering. Use `pmtiles_metadata()` to fetch details like layer names and map bounds, then style and add these tiles to your map. For instance, the example shows two layers: `buildings` styled in "steelblue" and `roads` styled in "black". + +```{code-cell} ipython3 +url = "https://open.gishub.org/data/pmtiles/protomaps_firenze.pmtiles" +metadata = leafmap.pmtiles_metadata(url) +print(f"layer names: {metadata['layer_names']}") +print(f"bounds: {metadata['bounds']}") +``` + +```{code-cell} ipython3 +m = leafmap.Map() + +style = { + "version": 8, + "sources": { + "example_source": { + "type": "vector", + "url": "pmtiles://" + url, + "attribution": "PMTiles", + } + }, + "layers": [ + { + "id": "buildings", + "source": "example_source", + "source-layer": "landuse", + "type": "fill", + "paint": {"fill-color": "steelblue"}, + }, + { + "id": "roads", + "source": "example_source", + "source-layer": "roads", + "type": "line", + "paint": {"line-color": "black"}, + }, + ], +} + +# style = leafmap.pmtiles_style(url) # Use default style + +m.add_pmtiles( + url, + style=style, + visible=True, + opacity=1.0, + tooltip=True, +) +m +``` + +```{code-cell} ipython3 +m.layer_interact() +``` + +### Source Cooperative Data + +Visualize the Google-Microsoft Open Buildings dataset, managed by VIDA, in PMTiles format. Fetch metadata to identify available layers, apply custom styles to the building footprints, and render them with semi-transparent colors for a clear visualization. + +Let's visualize the [Google-Microsoft Open Buildings - combined by VIDA](https://beta.source.coop/repositories/vida/google-microsoft-open-buildings/description). + +```{code-cell} ipython3 +url = "https://data.source.coop/vida/google-microsoft-open-buildings/pmtiles/go_ms_building_footprints.pmtiles" +metadata = leafmap.pmtiles_metadata(url) +print(f"layer names: {metadata['layer_names']}") +print(f"bounds: {metadata['bounds']}") +``` + +```{code-cell} ipython3 +m = leafmap.Map(center=[0, 20], zoom=2) +m.add_basemap("Google Hybrid", visible=False) + +style = { + "version": 8, + "sources": { + "example_source": { + "type": "vector", + "url": "pmtiles://" + url, + "attribution": "PMTiles", + } + }, + "layers": [ + { + "id": "buildings", + "source": "example_source", + "source-layer": "building_footprints", + "type": "fill", + "paint": {"fill-color": "#3388ff", "fill-opacity": 0.5}, + }, + ], +} + +# style = leafmap.pmtiles_style(url) # Use default style + +m.add_pmtiles( + url, + style=style, + visible=True, + opacity=1.0, + tooltip=True, +) +m +``` + +```{code-cell} ipython3 +m.layer_interact() +``` + +### 3D PMTiles + +Render global building data in 3D for a realistic, textured experience. Set building colors and extrusion heights to create visually compelling cityscapes. For example, apply color gradients and height scaling based on building attributes to differentiate buildings by their heights. + +```{code-cell} ipython3 +url = "https://data.source.coop/cholmes/overture/overture-buildings.pmtiles" +metadata = leafmap.pmtiles_metadata(url) +print(f"layer names: {metadata['layer_names']}") +print(f"bounds: {metadata['bounds']}") +``` + +```{code-cell} ipython3 +m = leafmap.Map( + center=[-74.0095, 40.7046], zoom=16, pitch=60, bearing=-17, style="positron" +) +m.add_basemap("OpenStreetMap.Mapnik") +m.add_basemap("Esri.WorldImagery", visible=False) + +style = { + "layers": [ + { + "id": "buildings", + "source": "example_source", + "source-layer": "buildings", + "type": "fill-extrusion", + "filter": [ + ">", + ["get", "height"], + 0, + ], # only show buildings with height info + "paint": { + "fill-extrusion-color": [ + "interpolate", + ["linear"], + ["get", "height"], + 0, + "lightgray", + 200, + "royalblue", + 400, + "lightblue", + ], + "fill-extrusion-height": ["*", ["get", "height"], 1], + }, + }, + ], +} + +m.add_pmtiles( + url, + style=style, + visible=True, + opacity=1.0, + tooltip=True, + template="Height: {{height}}
Country: {{country_iso}}", + fit_bounds=False, +) +m.add_layer_control() +m +``` + +### 3D Buildings + +For a simplified setup, the `add_overture_3d_buildings` function quickly adds 3D building data from Overture’s latest release to a basemap, creating depth and spatial realism on the map. + +```{code-cell} ipython3 +m = leafmap.Map( + center=[-74.0095, 40.7046], zoom=16, pitch=60, bearing=-17, style="positron" +) +m.add_basemap("Esri.WorldImagery", visible=False) +m.add_overture_3d_buildings(release="2024-09-18", template="simple") +m.add_layer_control() +m +``` + +### 2D Buildings, Transportation, and Other Themes + +Switch between specific Overture themes, such as `buildings`, `transportation`, `places`, or `addresses`, depending on the data focus. Each theme overlays relevant features with adjustable opacity for thematic visualization, providing easy customization for urban planning or transportation studies. + +Building theme: + +```{code-cell} ipython3 +m = leafmap.Map(center=[-74.0095, 40.7046], zoom=16) +m.add_basemap("Esri.WorldImagery", visible=False) +m.add_overture_data(theme="buildings", opacity=0.8) +m.add_layer_control() +m +``` + +Transportation theme: -The `urls` value is an array. For each URL in the array, a video element source will be created. To support the video across browsers, supply URLs in multiple formats. -The `coordinates` array contains [longitude, latitude] pairs for the video corners listed in clockwise order: top left, top right, bottom right, bottom left. +```{code-cell} ipython3 +m = leafmap.Map(center=[-74.0095, 40.7046], zoom=16) +m.add_basemap("Esri.WorldImagery", visible=False) +m.add_overture_data(theme="transportation", opacity=0.8) +m.add_layer_control() +m +``` + +Places theme: ```{code-cell} ipython3 -m = leafmap.Map( - center=[-122.514426, 37.562984], zoom=17, bearing=-96, style="satellite" -) -urls = [ - "https://static-assets.mapbox.com/mapbox-gl-js/drone.mp4", - "https://static-assets.mapbox.com/mapbox-gl-js/drone.webm", -] -coordinates = [ - [-122.51596391201019, 37.56238816766053], - [-122.51467645168304, 37.56410183312965], - [-122.51309394836426, 37.563391708549425], - [-122.51423120498657, 37.56161849366671], -] -m.add_video(urls, coordinates) +m = leafmap.Map(center=[-74.0095, 40.7046], zoom=16) +m.add_basemap("Esri.WorldImagery", visible=False) +m.add_overture_data(theme="places", opacity=0.8) m.add_layer_control() m ``` +Addresses theme: + ```{code-cell} ipython3 -m = leafmap.Map(center=[-115, 25], zoom=4, style="satellite") -urls = [ - "https://data.opengeos.org/patricia_nasa.mp4", - "https://data.opengeos.org/patricia_nasa.webm", -] -coordinates = [ - [-130, 32], - [-100, 32], - [-100, 13], - [-130, 13], -] -m.add_video(urls, coordinates) +m = leafmap.Map(center=[-74.0095, 40.7046], zoom=16) +m.add_basemap("Esri.WorldImagery", visible=False) +m.add_overture_data(theme="addresses", opacity=0.8) +m.add_layer_control() +m +``` + +Base theme: + +```{code-cell} ipython3 +m = leafmap.Map(center=[-74.0095, 40.7046], zoom=16) +m.add_basemap("Esri.WorldImagery", visible=False) +m.add_overture_data(theme="base", opacity=0.8) +m.add_layer_control() +m +``` + +Divisions themem: + +```{code-cell} ipython3 +m = leafmap.Map() +m.add_basemap("Esri.WorldImagery", visible=False) +m.add_overture_data(theme="divisions", opacity=0.8) m.add_layer_control() m ``` -## Deck.GL layers +## Deck.GL Layers -Deck.GL layers can be added to the map using the `add_deck_layer` method. +Integrate interactive, high-performance visualization layers using Deck.GL. Leafmap’s `add_deck_layer` method supports multiple Deck.GL layer types, including Grid, GeoJSON, and Arc layers. -### Single Deck.GL layer +### Single Deck.GL Layer + +Add a `GridLayer` to visualize point data, such as the density of bike parking in San Francisco. Customize the grid cell size, elevation, and color to represent data density visually and interactively. ```{code-cell} ipython3 m = leafmap.Map( @@ -1526,16 +2300,15 @@ m.add_deck_layers([deck_grid_layer], tooltip="Number of points: {{ count }}") m ``` -### Multiple Deck.GL layers +### Multiple Deck.GL Layers -```{code-cell} ipython3 -import requests -``` +Combine layers like `GeoJsonLayer` and `ArcLayer` for complex visualizations. For example: +1. Use `GeoJsonLayer` to show airports with varying point sizes based on significance. +2. Use `ArcLayer` to connect selected airports with London, coloring arcs to represent different paths. ```{code-cell} ipython3 -data = requests.get( - "https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_airports.geojson" -).json() +url = "https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_airports.geojson" +data = leafmap.read_geojson(url) ``` ```{code-cell} ipython3 @@ -1584,9 +2357,14 @@ m.add_deck_layers( m ``` +The result is a rich, interactive visualization that highlights both point data and relational data connections, useful for airport connectivity or hub-and-spoke modeling. + + ## Google Earth Engine -You can use the Earth Engine Python API to load and visualize Earth Engine data. +Leafmap enables integration with the Google Earth Engine (GEE) Python API, allowing for powerful visualization of Earth Engine datasets directly on a Leafmap map. + +To add Earth Engine layers, initialize a map and use `add_ee_layer` to add specific datasets, such as ESA WorldCover data. A legend can be included using `add_legend` to provide a visual reference. ```{code-cell} ipython3 m = leafmap.Map( @@ -1602,7 +2380,7 @@ m m.layer_interact() ``` -We can also overlay other data layers on top of Earth Engine data layers. +You can overlay Earth Engine data with other 3D elements, like buildings, to create a multi-layered, interactive map. If you have an Earth Engine account, authenticate and initialize Earth Engine in your notebook by uncommenting the relevant code. ```{code-cell} ipython3 m = leafmap.Map( @@ -1618,6 +2396,8 @@ If you have an Earth Engine, you can uncomment the first two code blocks to add ```{code-cell} ipython3 # import ee + +# ee.Authenticate() # ee.Initialize(project="YOUR-PROJECT-ID") ``` @@ -1631,9 +2411,260 @@ If you have an Earth Engine, you can uncomment the first two code blocks to add # m ``` +## Animations + +### Animate a Line + +Using Leafmap’s animation capabilities, you can animate a line by updating the coordinates of a GeoJSON line feature in real-time. The sample includes data loaded from a CSV file, which is sorted and plotted sequentially to show the line’s movement. + +```{code-cell} ipython3 +import time +import pandas as pd +``` + +```{code-cell} ipython3 +url = "https://github.com/opengeos/datasets/releases/download/world/animated_line_data.csv" +df = pd.read_csv(url) +df_sample = df.sample(n=1000, random_state=1).sort_index() +df_sample.loc[len(df_sample)] = df.iloc[-1] +df_sample.head() +``` + +```{code-cell} ipython3 +m = leafmap.Map(center=[0, 0], zoom=0.5, style="liberty") +geojson = { + "type": "FeatureCollection", + "features": [ + {"type": "Feature", "geometry": {"type": "LineString", "coordinates": [[0, 0]]}} + ], +} +source = {"type": "geojson", "data": geojson} +m.add_source("line", source) +layer = { + "id": "line-animation", + "type": "line", + "source": "line", + "layout": {"line-cap": "round", "line-join": "round"}, + "paint": {"line-color": "#ed6498", "line-width": 5, "line-opacity": 0.8}, +} +m.add_layer(layer) +m +``` + +```{code-cell} ipython3 +run_times = 2 +for i in range(run_times): + geojson["features"][0]["geometry"]["coordinates"] = [[0, 0]] + for row in df_sample.itertuples(): + time.sleep(0.005) + geojson["features"][0]["geometry"]["coordinates"].append([row.x, row.y]) + m.set_data("line", geojson) +``` + +### Animate the Map Camera Around a Point + +Control the map camera's rotation, zoom, and angle around a given point to create a smooth animation effect. This technique is especially useful for visualizing cityscapes or other 3D environments by making buildings appear dynamic. + +```{code-cell} ipython3 +m = leafmap.Map(center=[-87.62712, 41.89033], zoom=15, pitch=45, style="streets") +layers = m.get_style_layers() +for layer in layers: + if layer["type"] == "symbol" and ("text-field" in layer["layout"]): + m.remove_layer(layer["id"]) +layer = { + "id": "3d-buildings", + "source": "composite", + "source-layer": "building", + "filter": ["==", "extrude", "true"], + "type": "fill-extrusion", + "min_zoom": 15, + "paint": { + "fill-extrusion-color": "#aaa", + "fill-extrusion-height": [ + "interpolate", + ["linear"], + ["zoom"], + 15, + 0, + 15.05, + ["get", "height"], + ], + "fill-extrusion-base": [ + "interpolate", + ["linear"], + ["zoom"], + 15, + 0, + 15.05, + ["get", "min_height"], + ], + "fill-extrusion-opacity": 0.6, + }, +} +m.add_layer(layer) +m +``` + +### Animate a Point + +Animate a point along a circular path by computing points on a circle and updating the map. This is ideal for showing circular motion on the map, and can be customized for duration and frame rate to control the animation speed. + +```{code-cell} ipython3 +for degree in range(0, 180, 1): + m.rotate_to(degree, {"duration": 0}) + time.sleep(0.1) +``` + +```{code-cell} ipython3 +import math +``` + +```{code-cell} ipython3 +def point_on_circle(angle, radius): + return { + "type": "Point", + "coordinates": [math.cos(angle) * radius, math.sin(angle) * radius], + } +``` + +```{code-cell} ipython3 +m = leafmap.Map(center=[0, 0], zoom=2, style="liberty") +radius = 20 +source = {"type": "geojson", "data": point_on_circle(0, radius)} +m.add_source("point", source) +layer = { + "id": "point", + "source": "point", + "type": "circle", + "paint": {"circle-radius": 10, "circle-color": "#007cbf"}, +} +m.add_layer(layer) +m +``` + +```{code-cell} ipython3 +def animate_marker(duration, frame_rate, radius): + start_time = time.time() + while (time.time() - start_time) < duration: + timestamp = (time.time() - start_time) * 1000 # Convert to milliseconds + angle = timestamp / 1000 # Divisor controls the animation speed + point = point_on_circle(angle, radius) + m.set_data("point", point) + # Wait for the next frame + time.sleep(1 / frame_rate) +``` + +```{code-cell} ipython3 +duration = 10 # Duration of the animation in seconds +frame_rate = 30 # Frames per second +``` + +```{code-cell} ipython3 +animate_marker(duration, frame_rate, radius) +``` + +### Animate a Point Along a Route + +Create a point that follows a route specified by GeoJSON coordinates. For added realism, include rotation properties to simulate the direction of movement along the path. This animation is useful for tracking paths, such as vehicle or drone routes. + +```{code-cell} ipython3 +m = leafmap.Map(center=[-100, 40], zoom=3, style="streets") +url = "https://github.com/opengeos/datasets/releases/download/us/arc_with_bearings.geojson" +geojson = leafmap.read_geojson(url) +bearings = geojson["features"][0]["properties"]["bearings"] +coordinates = geojson["features"][0]["geometry"]["coordinates"][:-1] +m.add_geojson(geojson, name="route") + +origin = [-122.414, 37.776] +destination = [-77.032, 38.913] + +point = { + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": {}, + "geometry": {"type": "Point", "coordinates": origin}, + } + ], +} +source = {"type": "geojson", "data": point} +m.add_source("point", source) +layer = { + "id": "point", + "source": "point", + "type": "symbol", + "layout": { + "icon-image": "airport_15", + "icon-rotate": ["get", "bearing"], + "icon-rotation-alignment": "map", + "icon-overlap": "always", + "icon-ignore-placement": True, + }, +} +m.add_layer(layer) +m +``` + +```{code-cell} ipython3 +for index, coordinate in enumerate(coordinates): + point["features"][0]["geometry"]["coordinates"] = coordinate + point["features"][0]["properties"]["bearing"] = bearings[index] + m.set_data("point", point) + time.sleep(0.05) +``` + +### Update a Feature in Real-Time + +For applications such as tracking or tracing a path in real time, load data from a source like GeoDataFrame, append coordinates incrementally to a line feature, and update the map display as the path extends. + +```{code-cell} ipython3 +import geopandas as gpd +``` + +```{code-cell} ipython3 +m = leafmap.Map(center=[-122.019807, 45.632433], zoom=14, pitch=60, style="3d-terrain") +m +``` + +```{code-cell} ipython3 +url = "https://maplibre.org/maplibre-gl-js/docs/assets/hike.geojson" +gdf = gpd.read_file(url) +coordinates = list(gdf.geometry[0].coords) +print(coordinates[:5]) +``` + +```{code-cell} ipython3 +source = { + "type": "geojson", + "data": { + "type": "Feature", + "geometry": {"type": "LineString", "coordinates": [coordinates[0]]}, + }, +} +m.add_source("trace", source) +layer = { + "id": "trace", + "type": "line", + "source": "trace", + "paint": {"line-color": "yellow", "line-opacity": 0.75, "line-width": 5}, +} +m.add_layer(layer) +m.jump_to({"center": coordinates[0], "zoom": 14}) +m.set_pitch(30) +``` + +```{code-cell} ipython3 +for coord in coordinates: + time.sleep(0.005) + source["data"]["geometry"]["coordinates"].append(coord) + m.set_data("trace", source["data"]) + m.pan_to(coord) +``` + ## To HTML -To export the map as an HTML file, use the `to_html` method. To avoid exposing your private API key, you should create a public API key and restrict it to your website domain. +Export the final map to HTML using the `to_html` method. This allows you to share interactive maps online while keeping your private API keys secure. Create public API keys restricted to your website’s domain for safety. Customize the HTML output, including dimensions, title, and embedding options. ```{code-cell} ipython3 # import os @@ -1672,3 +2703,7 @@ m.to_html( ) m ``` + +## Summary + +In this lecture, we explored the functionality of the MapLibre library for creating and customizing interactive maps in Python. We covered how to build a map from scratch, add controls, and manage different basemaps. Additionally, we explored more complex visualizations, including 3D building and terrain views, layer customization, and data integration with GeoJSON and raster formats. By understanding and applying these techniques, students are now equipped to develop dynamic geospatial visualizations using MapLibre, enhancing both analytical and presentation capabilities in their GIS projects.