HGAC 2024
3D Mapping with MapLibre and Leafmap
Introduction¶
This notebook is for the workshop presented at the Houston Area GIS Day Workshops.
Attendees will learn how to create 3D maps using MapLibre and Leafmap. Topics include:
- Create interactive 2D maps with ipyleaflet
- Create interactive 3D maps with MapLibre
- Visualize 3D terrain, 3D buildings, and 3D indoor mapping
- Visualize local and cloud-based geospatial data, including COG, STAC, and PMTiles
- Add custom map components
- Export 3D maps as HTML for seamless website integration
Useful Resources¶
- MapLibre GL JS Documentation: Comprehensive documentation for MapLibre GL JS.
- MapLibre Python Bindings: Information on using MapLibre with Python.
- MapLibre in Leafmap: Examples and tutorials for MapLibre in Leafmap.
- Video Tutorials: Video guides for practical MapLibre skills.
- MapLibre Demos: Interactive demos showcasing MapLibre’s capabilities.
Installation and Setup¶
To install the required packages, uncomment and run the line below.
# %pip install -U "leafmap[maplibre]"
Once installed, import the maplibregl
backend from the leafmap
package:
import leafmap.maplibregl as leafmap
m = leafmap.Map()
m
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.
m = leafmap.Map(center=[-100, 40], zoom=3, pitch=0, bearing=0)
m
Hold down the Ctrl
key. Click and drag to pan the map.
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.
m = leafmap.Map(style="positron")
m
OpenFreeMap provides a variety of basemap styles that you can use in your interactive maps. These styles include liberty
, bright
, and positron
.
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.
m = leafmap.Map(style="background-lightgray")
m
Alternatively, you can provide a URL to a vector style.
style = "https://demotiles.maplibre.org/style.json"
m = leafmap.Map(style=style)
m
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.
Available Controls¶
- Geolocate: Centers the map based on the user’s current location, if available.
- Fullscreen: Expands the map to a full-screen view for better focus.
- 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.
m = leafmap.Map()
m.add_control("geolocate", position="top-left")
m
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.
m = leafmap.Map(center=[11.255, 43.77], zoom=13, style="positron", 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.
m = leafmap.Map(center=[11.255, 43.77], zoom=13, style="positron", 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.
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.
from maplibre.plugins import MapboxDrawControls, MapboxDrawOptions
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.
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.
m.draw_features_selected
m.draw_feature_collection_all
Adding 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.
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.
m = leafmap.Map()
m.add_basemap("OpenTopoMap")
m.add_layer_control()
m
m.add_basemap("Esri.WorldImagery")
You can also add basemaps interactively, which provides flexibility for selecting the best background for your map content.
m = leafmap.Map()
m
m.add_basemap()
Adding XYZ Tile Layer¶
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.
m = leafmap.Map()
url = "https://basemap.nationalmap.gov/arcgis/rest/services/USGSTopo/MapServer/tile/{z}/{y}/{x}"
m.add_tile_layer(url, name="USGS TOpo", attribution="USGS", opacity=1.0, visible=True)
m
Adding WMS Layer¶
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.
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
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()
m.add_legend(builtin_legend="NWI", title="Wetland Type")
m
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.
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,
}
],
}
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/.
# import os
# os.environ["MAPTILER_KEY"] = "YOUR_API_KEY"
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.
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.
m = leafmap.Map(style="streets")
m
m = leafmap.Map(style="satellite")
m
m = leafmap.Map(style="hybrid")
m
m = leafmap.Map(style="topo")
m
Adding a vector tile source¶
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_KEY = leafmap.get_api_key("MAPTILER_KEY")
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.
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
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
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
m = leafmap.Map(
center=[-122.1874314, 46.2022386],
zoom=13,
pitch=60,
bearing=220,
style="3d-terrain",
)
m.add_layer_control(bg_layers=True)
m
m = leafmap.Map(style="3d-ocean", exaggeration=1.5, hillshade=True)
m.add_layer_control(bg_layers=True)
m
3D Buildings¶
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.
m = leafmap.Map(
center=[-74.01201, 40.70473], zoom=16, pitch=60, bearing=35, style="basic-v2"
)
MAPTILER_KEY = leafmap.get_api_key("MAPTILER_KEY")
m.add_basemap("Esri.WorldImagery", visible=False)
source = {
"url": f"https://api.maptiler.com/tiles/v3/tiles.json?key={MAPTILER_KEY}",
"type": "vector",
}
layer = {
"id": "3d-buildings",
"source": "openmaptiles",
"source-layer": "building",
"type": "fill-extrusion",
"min-zoom": 15,
"paint": {
"fill-extrusion-color": [
"interpolate",
["linear"],
["get", "render_height"],
0,
"lightgray",
200,
"royalblue",
400,
"lightblue",
],
"fill-extrusion-height": [
"interpolate",
["linear"],
["zoom"],
15,
0,
16,
["get", "render_height"],
],
"fill-extrusion-base": [
"case",
[">=", ["get", "zoom"], 16],
["get", "render_min_height"],
0,
],
},
}
m.add_source("openmaptiles", source)
m.add_layer(layer)
m.add_layer_control()
m
m = leafmap.Map(
center=[-74.01201, 40.70473], zoom=16, pitch=60, bearing=35, style="basic-v2"
)
m.add_basemap("Esri.WorldImagery", visible=False)
m.add_3d_buildings(min_zoom=15)
m.add_layer_control()
m
3D Indoor Mapping¶
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.
data = "https://maplibre.org/maplibre-gl-js/docs/assets/indoor-3d-map.geojson"
gdf = leafmap.geojson_to_gdf(data)
gdf.explore()
gdf.head()
m = leafmap.Map(
center=(-87.61694, 41.86625), zoom=17, pitch=40, bearing=20, style="positron"
)
m.add_basemap("OpenStreetMap.Mapnik")
m.add_geojson(
data,
layer_type="fill-extrusion",
name="floorplan",
paint={
"fill-extrusion-color": ["get", "color"],
"fill-extrusion-height": ["get", "height"],
"fill-extrusion-base": ["get", "base_height"],
"fill-extrusion-opacity": 0.5,
},
)
m.add_layer_control()
m
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.
m = leafmap.Map(center=[19.43, 49.49], zoom=3, pitch=60, style="basic")
source = {
"type": "geojson",
"data": "https://docs.maptiler.com/sdk-js/assets/Mean_age_of_women_at_first_marriage_in_2019.geojson",
}
m.add_source("countries", source)
layer = {
"id": "eu-countries",
"source": "countries",
"type": "fill-extrusion",
"paint": {
"fill-extrusion-color": [
"interpolate",
["linear"],
["get", "age"],
23.0,
"#fff5eb",
24.0,
"#fee6ce",
25.0,
"#fdd0a2",
26.0,
"#fdae6b",
27.0,
"#fd8d3c",
28.0,
"#f16913",
29.0,
"#d94801",
30.0,
"#8c2d04",
],
"fill-extrusion-opacity": 1,
"fill-extrusion-height": ["*", ["get", "age"], 5000],
},
}
first_symbol_layer_id = m.find_first_symbol_layer()["id"]
m.add_layer(layer, first_symbol_layer_id)
m.add_layer_control()
m
m = leafmap.Map(center=[-100, 40], zoom=3, pitch=60, style="basic")
source = {
"type": "geojson",
"data": "https://open.gishub.org/data/us/us_counties.geojson",
}
m.add_source("counties", source)
layer = {
"id": "us-counties",
"source": "counties",
"type": "fill-extrusion",
"paint": {
"fill-extrusion-color": [
"interpolate",
["linear"],
["get", "CENSUSAREA"],
400,
"#fff5eb",
600,
"#fee6ce",
800,
"#fdd0a2",
1000,
"#fdae6b",
],
"fill-extrusion-opacity": 1,
"fill-extrusion-height": ["*", ["get", "CENSUSAREA"], 50],
},
}
first_symbol_layer_id = m.find_first_symbol_layer()["id"]
m.add_layer(layer, first_symbol_layer_id)
m.add_layer_control()
m
Visualizing 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.
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.
m = leafmap.Map(center=[12.550343, 55.665957], zoom=8, style="positron")
m.add_marker(lng_lat=[12.550343, 55.665957])
m
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
url = (
"https://github.com/opengeos/datasets/releases/download/world/world_cities.geojson"
)
geojson = leafmap.read_geojson(url)
m = leafmap.Map(style="streets")
m.add_geojson(geojson, name="cities")
m.add_popup("cities")
m
m = leafmap.Map(style="streets")
source = {"type": "geojson", "data": geojson}
layer = {
"id": "cities",
"type": "symbol",
"source": "point",
"layout": {
"icon-image": "marker_15",
"icon-size": 1,
},
}
m.add_source("point", source)
m.add_layer(layer)
m.add_popup("cities")
m
Customizing 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.
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.
m = leafmap.Map(center=[-122.486052, 37.830348], zoom=15, style="streets")
source = {
"type": "geojson",
"data": {
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"coordinates": [
[-122.48369693756104, 37.83381888486939],
[-122.48348236083984, 37.83317489144141],
[-122.48339653015138, 37.83270036637107],
[-122.48356819152832, 37.832056363179625],
[-122.48404026031496, 37.83114119107971],
[-122.48404026031496, 37.83049717427869],
[-122.48348236083984, 37.829920943955045],
[-122.48356819152832, 37.82954808664175],
[-122.48507022857666, 37.82944639795659],
[-122.48610019683838, 37.82880236636284],
[-122.48695850372314, 37.82931081282506],
[-122.48700141906738, 37.83080223556934],
[-122.48751640319824, 37.83168351665737],
[-122.48803138732912, 37.832158048267786],
[-122.48888969421387, 37.83297152392784],
[-122.48987674713133, 37.83263257682617],
[-122.49043464660643, 37.832937629287755],
[-122.49125003814696, 37.832429207817725],
[-122.49163627624512, 37.832564787218985],
[-122.49223709106445, 37.83337825839438],
[-122.49378204345702, 37.83368330777276],
],
},
},
}
layer = {
"id": "route",
"type": "line",
"source": "route",
"layout": {"line-join": "round", "line-cap": "round"},
"paint": {"line-color": "#888", "line-width": 8},
}
m.add_source("route", source)
m.add_layer(layer)
m
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.
m = leafmap.Map(center=[-68.137343, 45.137451], zoom=5, style="streets")
geojson = {
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-67.13734351262877, 45.137451890638886],
[-66.96466, 44.8097],
[-68.03252, 44.3252],
[-69.06, 43.98],
[-70.11617, 43.68405],
[-70.64573401557249, 43.090083319667144],
[-70.75102474636725, 43.08003225358635],
[-70.79761105007827, 43.21973948828747],
[-70.98176001655037, 43.36789581966826],
[-70.94416541205806, 43.46633942318431],
[-71.08482, 45.3052400000002],
[-70.6600225491012, 45.46022288673396],
[-70.30495378282376, 45.914794623389355],
[-70.00014034695016, 46.69317088478567],
[-69.23708614772835, 47.44777598732787],
[-68.90478084987546, 47.184794623394396],
[-68.23430497910454, 47.35462921812177],
[-67.79035274928509, 47.066248887716995],
[-67.79141211614706, 45.702585354182816],
[-67.13734351262877, 45.137451890638886],
]
],
},
}
source = {"type": "geojson", "data": geojson}
m.add_source("maine", source)
layer = {
"id": "maine",
"type": "fill",
"source": "maine",
"layout": {},
"paint": {"fill-color": "#088", "fill-opacity": 0.8},
}
m.add_layer(layer)
m
m = leafmap.Map(center=[-68.137343, 45.137451], zoom=5, style="streets")
paint = {"fill-color": "#088", "fill-opacity": 0.8}
m.add_geojson(geojson, layer_type="fill", paint=paint)
m
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
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.
m = leafmap.Map(
center=[-123.13, 49.254], zoom=11, style="dark-matter", pitch=45, bearing=0
)
url = "https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/geojson/vancouver-blocks.json"
paint_line = {
"line-color": "white",
"line-width": 2,
}
paint_fill = {
"fill-extrusion-color": {
"property": "valuePerSqm",
"stops": [
[0, "grey"],
[1000, "yellow"],
[5000, "orange"],
[10000, "darkred"],
[50000, "lightblue"],
],
},
"fill-extrusion-height": ["*", 10, ["sqrt", ["get", "valuePerSqm"]]],
"fill-extrusion-opacity": 0.9,
}
m.add_geojson(url, layer_type="line", paint=paint_line, name="blocks-line")
m.add_geojson(url, layer_type="fill-extrusion", paint=paint_fill, name="blocks-fill")
m
m.layer_interact()
Marker Cluster¶
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.
m = leafmap.Map(center=[-103.59179, 40.66995], zoom=3, style="streets")
data = "https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson"
source_args = {
"cluster": True,
"cluster_radius": 50,
"cluster_min_points": 2,
"cluster_max_zoom": 14,
"cluster_properties": {
"maxMag": ["max", ["get", "mag"]],
"minMag": ["min", ["get", "mag"]],
},
}
m.add_geojson(
data,
layer_type="circle",
name="earthquake-circles",
filter=["!", ["has", "point_count"]],
paint={"circle-color": "darkblue"},
source_args=source_args,
)
m.add_geojson(
data,
layer_type="circle",
name="earthquake-clusters",
filter=["has", "point_count"],
paint={
"circle-color": [
"step",
["get", "point_count"],
"#51bbd6",
100,
"#f1f075",
750,
"#f28cb1",
],
"circle-radius": ["step", ["get", "point_count"], 20, 100, 30, 750, 40],
},
source_args=source_args,
)
m.add_geojson(
data,
layer_type="symbol",
name="earthquake-labels",
filter=["has", "point_count"],
layout={
"text-field": ["get", "point_count_abbreviated"],
"text-size": 12,
},
source_args=source_args,
)
m
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
.
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 = leafmap.Map(center=[-100, 40], zoom=3)
m
m.open_geojson()
Changing 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.
m = leafmap.Map(center=[-90.73414, 14.55524], zoom=13, style="basic")
m.set_paint_property(
"building",
"fill-color",
["interpolate", ["exponential", 0.5], ["zoom"], 15, "#e2714b", 22, "#eee695"],
)
m.set_paint_property(
"building",
"fill-opacity",
["interpolate", ["exponential", 0.5], ["zoom"], 15, 0, 22, 1],
)
m.add_layer_control(bg_layers=True)
m
m.add_call("zoomTo", 19, {"duration": 9000})
Adding a New Layer Below Labels¶
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.
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",
}
m.add_source("urban-areas", source)
first_symbol_layer = m.find_first_symbol_layer()
layer = {
"id": "urban-areas-fill",
"type": "fill",
"source": "urban-areas",
"layout": {},
"paint": {"fill-color": "#f08", "fill-opacity": 0.4},
}
m.add_layer(layer, before_id=first_symbol_layer["id"])
m
Heat Map¶
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.
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
Visualizing Population Density¶
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.
m = leafmap.Map(center=[30.0222, -1.9596], zoom=7, style="streets")
source = {
"type": "geojson",
"data": "https://maplibre.org/maplibre-gl-js/docs/assets/rwanda-provinces.geojson",
}
m.add_source("rwanda-provinces", source)
layer = {
"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
Visualizing 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:
- 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
andvmax
arguments to improve clarity.
url = "https://github.com/opengeos/datasets/releases/download/raster/landsat.tif"
filepath = "landsat.tif"
leafmap.download_file(url, filepath, quiet=True)
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
m.layer_interact()
A Digital Elevation Model (DEM) is also downloaded and visualized with a terrain color scheme. Leafmap’s layer_interact
method allows interactive adjustments.
url = "https://github.com/opengeos/datasets/releases/download/raster/srtm90.tif"
filepath = "srtm90.tif"
leafmap.download_file(url, filepath, quiet=True)
m = leafmap.Map(style="satellite")
m.add_raster(filepath, colormap="terrain", name="DEM")
m
m.layer_interact()
Cloud Optimized GeoTIFF (COG)¶
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.
m = leafmap.Map(style="satellite")
before = (
"https://github.com/opengeos/datasets/releases/download/raster/Libya-2023-07-01.tif"
)
after = (
"https://github.com/opengeos/datasets/releases/download/raster/Libya-2023-09-13.tif"
)
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
m.layer_interact()
STAC Layer¶
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.
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=["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
m.layer_interact()
Leafmap also supports loading STAC items from the Microsoft Planetary Computer. The example demonstrates how to load a STAC item from the Planetary Computer and display it on the map.
collection = "landsat-8-c2-l2"
item = "LC08_L2SP_047027_20201204_02_T1"
leafmap.stac_assets(collection=collection, item=item, titiler_endpoint="pc")
m = leafmap.Map(style="satellite")
m.add_stac_layer(
collection=collection,
item=item,
assets=["SR_B5", "SR_B4", "SR_B3"],
name="Color infrared",
)
m
m = leafmap.Map(
center=[-122.65, 45.52], zoom=9, interactive=False, style="liberty", controls={}
)
m
Disabling Scroll Zoom¶
Use scroll_zoom=False
to prevent map zooming with the scroll wheel, maintaining a fixed zoom level.
m = leafmap.Map(center=[-122.65, 45.52], zoom=9, scroll_zoom=False, style="liberty")
m
Fitting Bounds¶
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.
m = leafmap.Map(center=[-74.5, 40], zoom=9, style="liberty")
m
Fit to Kenya.
bounds = [[32.958984, -5.353521], [43.50585, 5.615985]]
m.fit_bounds(bounds)
m = leafmap.Map(center=[-77.0214, 38.897], zoom=12, style="liberty")
geojson = {
"type": "FeatureCollection",
"features": [
{
"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],
],
},
}
],
}
m.add_source("LineString", {"type": "geojson", "data": geojson})
layer = {
"id": "LineString",
"type": "line",
"source": "LineString",
"layout": {"line-join": "