| Title: | Interactive Maps with 'Mapbox GL JS' and 'MapLibre GL JS' |
|---|---|
| Description: | Provides an interface to the 'Mapbox GL JS' (<https://docs.mapbox.com/mapbox-gl-js/guides>) and the 'MapLibre GL JS' (<https://maplibre.org/maplibre-gl-js/docs/>) interactive mapping libraries to help users create custom interactive maps in R. Users can create interactive globe visualizations; layer 'sf' objects to create filled maps, circle maps, 'heatmaps', and three-dimensional graphics; and customize map styles and views. The package also includes utilities to use 'Mapbox' and 'MapLibre' maps in 'Shiny' web applications. |
| Authors: | Kyle Walker [aut, cre], Egor Kotov [aut, ctb] (ORCID: <https://orcid.org/0000-0001-6690-5345>, added Flowmap.gl, layer tuner, time control) |
| Maintainer: | Kyle Walker <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.4.9.9000 |
| Built: | 2026-06-01 21:04:30 UTC |
| Source: | https://github.com/e-kotov/mapgl |
Add a bivariate legend
add_bivariate_legend( map, scale, legend_title = NULL, x_title = NULL, y_title = NULL, position = "top-left", width = NULL, style = NULL, add = FALSE, unique_id = NULL, layer_id = NULL, target = "compare", draggable = FALSE, collapsible = FALSE, collapsed = FALSE )add_bivariate_legend( map, scale, legend_title = NULL, x_title = NULL, y_title = NULL, position = "top-left", width = NULL, style = NULL, add = FALSE, unique_id = NULL, layer_id = NULL, target = "compare", draggable = FALSE, collapsible = FALSE, collapsed = FALSE )
map |
A map object created by |
scale |
A |
legend_title |
Optional legend title. |
x_title |
Label for the horizontal axis. Defaults to the x column name. |
y_title |
Label for the vertical axis. Defaults to the y column name. |
position |
The legend position. |
width |
Legend width. |
style |
Optional styling options from |
add |
Logical, whether to add to existing legends. |
unique_id |
Optional unique legend ID. |
layer_id |
Optional associated layer ID for layer-control show/hide. |
target |
For compare objects, one of |
draggable |
Logical, whether the legend can be dragged. |
collapsible |
Logical, whether the legend can collapse. |
collapsed |
Logical, whether the legend starts collapsed. |
The updated map object.
Add a circle layer to a Mapbox GL map
add_circle_layer( map, id, source, source_layer = NULL, circle_blur = NULL, circle_color = NULL, circle_emissive_strength = NULL, circle_opacity = NULL, circle_pitch_alignment = NULL, circle_pitch_scale = NULL, circle_radius = NULL, circle_sort_key = NULL, circle_stroke_color = NULL, circle_stroke_opacity = NULL, circle_stroke_width = NULL, circle_translate = NULL, circle_translate_anchor = "map", visibility = "visible", slot = NULL, min_zoom = NULL, max_zoom = NULL, popup = NULL, tooltip = NULL, hover_options = NULL, before_id = NULL, filter = NULL, cluster_options = NULL )add_circle_layer( map, id, source, source_layer = NULL, circle_blur = NULL, circle_color = NULL, circle_emissive_strength = NULL, circle_opacity = NULL, circle_pitch_alignment = NULL, circle_pitch_scale = NULL, circle_radius = NULL, circle_sort_key = NULL, circle_stroke_color = NULL, circle_stroke_opacity = NULL, circle_stroke_width = NULL, circle_translate = NULL, circle_translate_anchor = "map", visibility = "visible", slot = NULL, min_zoom = NULL, max_zoom = NULL, popup = NULL, tooltip = NULL, hover_options = NULL, before_id = NULL, filter = NULL, cluster_options = NULL )
map |
A map object created by the |
id |
A unique ID for the layer. |
source |
The ID of the source, alternatively an sf object (which will be converted to a GeoJSON source) or a named list that specifies |
source_layer |
The source layer (for vector sources). |
circle_blur |
Amount to blur the circle. |
circle_color |
The color of the circle. |
circle_emissive_strength |
Controls the intensity of light emitted on the source features. Requires 3D lights. |
circle_opacity |
The opacity at which the circle will be drawn. |
circle_pitch_alignment |
Orientation of circles when the map is pitched. One of |
circle_pitch_scale |
Controls the scaling behavior of circles when the map is pitched. One of |
circle_radius |
Circle radius. |
circle_sort_key |
Sorts features in ascending order based on this value. |
circle_stroke_color |
The color of the circle's stroke. |
circle_stroke_opacity |
The opacity of the circle's stroke. |
circle_stroke_width |
The width of the circle's stroke. |
circle_translate |
The geometry's offset. Values are |
circle_translate_anchor |
Controls the frame of reference for |
visibility |
Whether this layer is displayed. |
slot |
An optional slot for layer order. |
min_zoom |
The minimum zoom level for the layer. |
max_zoom |
The maximum zoom level for the layer. |
popup |
A column name containing information to display in a popup on click. Columns containing HTML will be parsed. |
tooltip |
A column name containing information to display in a tooltip on hover. Columns containing HTML will be parsed. |
hover_options |
A named list of options for highlighting features in the layer on hover. |
before_id |
The name of the layer that this layer appears "before", allowing you to insert layers below other layers in your basemap (e.g. labels). |
filter |
An optional filter expression to subset features in the layer. |
cluster_options |
A list of options for clustering circles, created by the Updating a clustered layer in Shiny: the shortcut creates three layers ( |
The modified map object with the new circle layer added.
## Not run: library(mapgl) library(sf) library(dplyr) # Set seed for reproducibility set.seed(1234) # Define the bounding box for Washington DC (approximately) bbox <- st_bbox( c( xmin = -77.119759, ymin = 38.791645, xmax = -76.909393, ymax = 38.995548 ), crs = st_crs(4326) ) # Generate 30 random points within the bounding box random_points <- st_as_sf( data.frame( id = 1:30, lon = runif(30, bbox["xmin"], bbox["xmax"]), lat = runif(30, bbox["ymin"], bbox["ymax"]) ), coords = c("lon", "lat"), crs = 4326 ) # Assign random categories categories <- c("music", "bar", "theatre", "bicycle") random_points <- random_points %>% mutate(category = sample(categories, n(), replace = TRUE)) # Map with circle layer mapboxgl(style = mapbox_style("light")) %>% fit_bounds(random_points, animate = FALSE) %>% add_circle_layer( id = "poi-layer", source = random_points, circle_color = match_expr( "category", values = c( "music", "bar", "theatre", "bicycle" ), stops = c( "#1f78b4", "#33a02c", "#e31a1c", "#ff7f00" ) ), circle_radius = 8, circle_stroke_color = "#ffffff", circle_stroke_width = 2, circle_opacity = 0.8, tooltip = "category", hover_options = list( circle_radius = 12, circle_color = "#ffff99" ) ) %>% add_categorical_legend( legend_title = "Points of Interest", values = c("Music", "Bar", "Theatre", "Bicycle"), colors = c("#1f78b4", "#33a02c", "#e31a1c", "#ff7f00"), circular_patches = TRUE ) ## End(Not run)## Not run: library(mapgl) library(sf) library(dplyr) # Set seed for reproducibility set.seed(1234) # Define the bounding box for Washington DC (approximately) bbox <- st_bbox( c( xmin = -77.119759, ymin = 38.791645, xmax = -76.909393, ymax = 38.995548 ), crs = st_crs(4326) ) # Generate 30 random points within the bounding box random_points <- st_as_sf( data.frame( id = 1:30, lon = runif(30, bbox["xmin"], bbox["xmax"]), lat = runif(30, bbox["ymin"], bbox["ymax"]) ), coords = c("lon", "lat"), crs = 4326 ) # Assign random categories categories <- c("music", "bar", "theatre", "bicycle") random_points <- random_points %>% mutate(category = sample(categories, n(), replace = TRUE)) # Map with circle layer mapboxgl(style = mapbox_style("light")) %>% fit_bounds(random_points, animate = FALSE) %>% add_circle_layer( id = "poi-layer", source = random_points, circle_color = match_expr( "category", values = c( "music", "bar", "theatre", "bicycle" ), stops = c( "#1f78b4", "#33a02c", "#e31a1c", "#ff7f00" ) ), circle_radius = 8, circle_stroke_color = "#ffffff", circle_stroke_width = 2, circle_opacity = 0.8, tooltip = "category", hover_options = list( circle_radius = 12, circle_color = "#ffff99" ) ) %>% add_categorical_legend( legend_title = "Points of Interest", values = c("Music", "Bar", "Theatre", "Bicycle"), colors = c("#1f78b4", "#33a02c", "#e31a1c", "#ff7f00"), circular_patches = TRUE ) ## End(Not run)
This function adds a custom control to a Mapbox GL or MapLibre GL map. It allows you to create custom HTML element controls and add them to the map.
add_control( map, html, position = "top-right", className = NULL, id = NULL, ... )add_control( map, html, position = "top-right", className = NULL, id = NULL, ... )
map |
A map object created by the |
html |
Character string containing the HTML content for the control. |
position |
The position of the control. Can be one of "top-left", "top-right", "bottom-left", or "bottom-right". Default is "top-right". |
className |
Optional CSS class name for the control container. |
id |
Optional unique identifier for the control. If not provided, defaults to "custom".
This ID can be used with |
... |
Additional arguments passed to the JavaScript side. |
The modified map object with the custom control added.
## Not run: library(mapgl) # Basic custom control maplibre() |> add_control( html = "<div style='background-color: white; padding: 5px;'> <p>Custom HTML</p> <img src='path/to/image.png' alt='image'/> </div>", position = "top-left" ) # Custom control with specific ID for selective removal maplibre() |> add_control( html = "<div style='background: blue; color: white; padding: 10px;'> My Control </div>", position = "top-right", id = "my_custom_control" ) # Later, remove only this specific control maplibre_proxy("map") |> clear_controls("my_custom_control") ## End(Not run)## Not run: library(mapgl) # Basic custom control maplibre() |> add_control( html = "<div style='background-color: white; padding: 5px;'> <p>Custom HTML</p> <img src='path/to/image.png' alt='image'/> </div>", position = "top-left" ) # Custom control with specific ID for selective removal maplibre() |> add_control( html = "<div style='background: blue; color: white; padding: 10px;'> My Control </div>", position = "top-right", id = "my_custom_control" ) # Later, remove only this specific control maplibre_proxy("map") |> clear_controls("my_custom_control") ## End(Not run)
This function adds a compact control that displays the cursor position as longitude and latitude in WGS84 coordinates.
add_coordinates_control( map, position = "bottom-right", format = c("decimal", "dms"), precision = NULL, label = NULL, empty_text = "Move cursor over map", wrap = TRUE )add_coordinates_control( map, position = "bottom-right", format = c("decimal", "dms"), precision = NULL, label = NULL, empty_text = "Move cursor over map", wrap = TRUE )
map |
A map object created by the |
position |
The position of the control. Can be one of "top-left", "top-right", "bottom-left", or "bottom-right". Default is "bottom-right". |
format |
Coordinate display format. One of |
precision |
Number of decimal places to display. If |
label |
Optional label shown above the coordinates. Default is |
empty_text |
Text shown before the cursor enters the map, and after it leaves the map. |
wrap |
Logical. If |
The modified map object with the coordinates control added.
## Not run: library(mapgl) maplibre() |> add_coordinates_control() mapboxgl() |> add_coordinates_control( position = "bottom-left", format = "dms", precision = 2, label = "Longitude, latitude" ) ## End(Not run)## Not run: library(mapgl) maplibre() |> add_coordinates_control() mapboxgl() |> add_coordinates_control( position = "bottom-left", format = "dms", precision = 2, label = "Longitude, latitude" ) ## End(Not run)
Add a draw control to a map
add_draw_control( map, position = "top-left", freehand = FALSE, simplify_freehand = FALSE, rectangle = FALSE, radius = FALSE, bezier = FALSE, bezier_polygon = FALSE, orientation = "vertical", source = NULL, attributes = NULL, point_color = "#3bb2d0", line_color = "#3bb2d0", fill_color = "#3bb2d0", fill_opacity = 0.1, active_color = "#fbb03b", vertex_radius = 5, line_width = 2, download_button = FALSE, download_filename = "drawn-features", show_measurements = FALSE, measurement_units = "both", ... )add_draw_control( map, position = "top-left", freehand = FALSE, simplify_freehand = FALSE, rectangle = FALSE, radius = FALSE, bezier = FALSE, bezier_polygon = FALSE, orientation = "vertical", source = NULL, attributes = NULL, point_color = "#3bb2d0", line_color = "#3bb2d0", fill_color = "#3bb2d0", fill_opacity = 0.1, active_color = "#fbb03b", vertex_radius = 5, line_width = 2, download_button = FALSE, download_filename = "drawn-features", show_measurements = FALSE, measurement_units = "both", ... )
map |
A map object created by the |
position |
A string specifying the position of the draw control. One of "top-right", "top-left", "bottom-right", or "bottom-left". |
freehand |
Logical, whether to enable freehand drawing mode. Default is FALSE. |
simplify_freehand |
Logical, whether to apply simplification to freehand drawings. Default is FALSE. |
rectangle |
Logical, whether to enable rectangle drawing mode. Default is FALSE. |
radius |
Logical, whether to enable radius/circle drawing mode. Default is FALSE. |
bezier |
Logical, whether to enable Bezier curve drawing mode. Default is FALSE. |
bezier_polygon |
Logical, whether to enable Bezier polygon drawing mode. Default is FALSE. |
orientation |
A string specifying the orientation of the draw control. Either "vertical" (default) or "horizontal". |
source |
A character string specifying a source ID to add to the draw control. Default is NULL. |
attributes |
Optional named list defining editable feature attributes.
Use |
point_color |
Color for point features. Default is "#3bb2d0" (light blue). |
line_color |
Color for line features. Default is "#3bb2d0" (light blue). |
fill_color |
Fill color for polygon features. Default is "#3bb2d0" (light blue). |
fill_opacity |
Fill opacity for polygon features. Default is 0.1. |
active_color |
Color for active (selected) features. Default is "#fbb03b" (orange). |
vertex_radius |
Radius of vertex points in pixels. Default is 5. |
line_width |
Width of lines in pixels. Default is 2. |
download_button |
Logical, whether to add a download button to export drawn features as GeoJSON. Default is FALSE. |
download_filename |
Base filename for downloaded GeoJSON (without extension). Default is "drawn-features". |
show_measurements |
Logical, whether to show live measurements while drawing. Default is FALSE. |
measurement_units |
Units for measurements. Either "metric", "imperial", or "both". Default is "both". |
... |
Additional named arguments. See https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md#options for a list of options. |
Bezier drawing modes are supported when the draw control is added to the original map widget or later through a regular Shiny map proxy. Compare widgets and compare proxies are not yet supported for Bezier modes.
To draw Bezier curves, click the Bezier button, then use Alt + left-drag to create nodes with handles. A plain left-click creates nodes without handles. Press Enter, or click the last node, to finish the curve. In direct select mode, select a node and drag its handles to edit the curve; use Alt + drag on a handle to break handle symmetry.
Retrieved Bezier features are returned to R as standard sf geometries using the rendered curved coordinates: Bezier curves become LineString features and Bezier polygons become Polygon features. The Bezier control metadata is also preserved in feature-property columns so the browser widget can continue to edit those features as Bezier objects.
When attributes is supplied, selecting exactly one drawn feature opens a
small attribute editor. Click Save to write values to the feature properties;
get_drawn_features() returns those properties as sf columns. The editor
works for newly drawn features and features loaded into the draw control with
source or add_features_to_draw(). Compare widgets are not yet supported
for attribute editing.
The modified map object with the draw control added.
## Not run: library(mapgl) mapboxgl( style = mapbox_style("streets"), center = c(-74.50, 40), zoom = 9 ) |> add_draw_control() # With initial features from a source library(tigris) tx <- counties(state = "TX", cb = TRUE) mapboxgl(bounds = tx) |> add_source(id = "tx", data = tx) |> add_draw_control(source = "tx") # With custom styling mapboxgl() |> add_draw_control( point_color = "#ff0000", line_color = "#00ff00", fill_color = "#0000ff", fill_opacity = 0.3, active_color = "#ff00ff", vertex_radius = 7, line_width = 3 ) # Enable rectangle drawing mode mapboxgl() |> add_draw_control(rectangle = TRUE) # Enable radius/circle drawing mode mapboxgl() |> add_draw_control(radius = TRUE) # Enable Bezier curve drawing mode mapboxgl() |> add_draw_control(bezier = TRUE) # Add an attribute editor for classification workflows mapboxgl() |> add_draw_control( attributes = list( class = draw_attribute( "select", choices = c("forest", "water", "urban"), required = TRUE ), notes = draw_attribute("textarea"), confidence = draw_attribute( "numeric", min = 0, max = 1, step = 0.1, default = 1 ) ) ) # Enable multiple drawing modes mapboxgl() |> add_draw_control( freehand = TRUE, rectangle = TRUE, radius = TRUE, bezier = TRUE ) ## End(Not run)## Not run: library(mapgl) mapboxgl( style = mapbox_style("streets"), center = c(-74.50, 40), zoom = 9 ) |> add_draw_control() # With initial features from a source library(tigris) tx <- counties(state = "TX", cb = TRUE) mapboxgl(bounds = tx) |> add_source(id = "tx", data = tx) |> add_draw_control(source = "tx") # With custom styling mapboxgl() |> add_draw_control( point_color = "#ff0000", line_color = "#00ff00", fill_color = "#0000ff", fill_opacity = 0.3, active_color = "#ff00ff", vertex_radius = 7, line_width = 3 ) # Enable rectangle drawing mode mapboxgl() |> add_draw_control(rectangle = TRUE) # Enable radius/circle drawing mode mapboxgl() |> add_draw_control(radius = TRUE) # Enable Bezier curve drawing mode mapboxgl() |> add_draw_control(bezier = TRUE) # Add an attribute editor for classification workflows mapboxgl() |> add_draw_control( attributes = list( class = draw_attribute( "select", choices = c("forest", "water", "urban"), required = TRUE ), notes = draw_attribute("textarea"), confidence = draw_attribute( "numeric", min = 0, max = 1, step = 0.1, default = 1 ) ) ) # Enable multiple drawing modes mapboxgl() |> add_draw_control( freehand = TRUE, rectangle = TRUE, radius = TRUE, bezier = TRUE ) ## End(Not run)
This function adds features from an existing source to a draw control on a map.
add_features_to_draw(map, source, clear_existing = FALSE)add_features_to_draw(map, source, clear_existing = FALSE)
map |
A map object with a draw control already added |
source |
Character string specifying a source ID to get features from |
clear_existing |
Logical, whether to clear existing drawn features before adding new ones. Default is FALSE. |
The modified map object
## Not run: library(mapgl) library(tigris) # Add features from an existing source tx <- counties(state = "TX", cb = TRUE) mapboxgl(bounds = tx) |> add_source(id = "tx", data = tx) |> add_draw_control() |> add_features_to_draw(source = "tx") # In a Shiny app observeEvent(input$load_data, { mapboxgl_proxy("map") |> add_features_to_draw( source = "dynamic_data", clear_existing = TRUE ) }) ## End(Not run)## Not run: library(mapgl) library(tigris) # Add features from an existing source tx <- counties(state = "TX", cb = TRUE) mapboxgl(bounds = tx) |> add_source(id = "tx", data = tx) |> add_draw_control() |> add_features_to_draw(source = "tx") # In a Shiny app observeEvent(input$load_data, { mapboxgl_proxy("map") |> add_features_to_draw( source = "dynamic_data", clear_existing = TRUE ) }) ## End(Not run)
Add a fill-extrusion layer to a Mapbox GL map
add_fill_extrusion_layer( map, id, source, source_layer = NULL, fill_extrusion_ambient_occlusion_intensity = NULL, fill_extrusion_ambient_occlusion_radius = NULL, fill_extrusion_base = NULL, fill_extrusion_cast_shadows = NULL, fill_extrusion_color = NULL, fill_extrusion_cutoff_fade_range = NULL, fill_extrusion_emissive_strength = NULL, fill_extrusion_height = NULL, fill_extrusion_opacity = NULL, fill_extrusion_pattern = NULL, fill_extrusion_translate = NULL, fill_extrusion_translate_anchor = "map", fill_extrusion_vertical_gradient = NULL, visibility = "visible", slot = NULL, min_zoom = NULL, max_zoom = NULL, popup = NULL, tooltip = NULL, hover_options = NULL, before_id = NULL, filter = NULL )add_fill_extrusion_layer( map, id, source, source_layer = NULL, fill_extrusion_ambient_occlusion_intensity = NULL, fill_extrusion_ambient_occlusion_radius = NULL, fill_extrusion_base = NULL, fill_extrusion_cast_shadows = NULL, fill_extrusion_color = NULL, fill_extrusion_cutoff_fade_range = NULL, fill_extrusion_emissive_strength = NULL, fill_extrusion_height = NULL, fill_extrusion_opacity = NULL, fill_extrusion_pattern = NULL, fill_extrusion_translate = NULL, fill_extrusion_translate_anchor = "map", fill_extrusion_vertical_gradient = NULL, visibility = "visible", slot = NULL, min_zoom = NULL, max_zoom = NULL, popup = NULL, tooltip = NULL, hover_options = NULL, before_id = NULL, filter = NULL )
map |
A map object created by the |
id |
A unique ID for the layer. |
source |
The ID of the source, alternatively an sf object (which will be converted to a GeoJSON source) or a named list that specifies |
source_layer |
The source layer (for vector sources). |
fill_extrusion_ambient_occlusion_intensity |
Controls the intensity of ambient occlusion shading. Value between 0 and 1; around 0.3 provides the most plausible results for buildings. |
fill_extrusion_ambient_occlusion_radius |
Shades area near ground and concave angles between walls. Default 3.0 corresponds to one floor height. |
fill_extrusion_base |
The base height of the fill extrusion. |
fill_extrusion_cast_shadows |
If |
fill_extrusion_color |
The color of the fill extrusion. |
fill_extrusion_cutoff_fade_range |
Defines the fade-out range before automatic content cutoff on pitched views. Value between 0 and 1; 0 disables cutoff. |
fill_extrusion_emissive_strength |
Controls the intensity of light emitted on the source features. Requires 3D lights. |
fill_extrusion_height |
The height of the fill extrusion. |
fill_extrusion_opacity |
The opacity of the fill extrusion. |
fill_extrusion_pattern |
Name of image in sprite to use for drawing image fills. |
fill_extrusion_translate |
The geometry's offset. Values are |
fill_extrusion_translate_anchor |
Controls the frame of reference for |
fill_extrusion_vertical_gradient |
If |
visibility |
Whether this layer is displayed. |
slot |
An optional slot for layer order. |
min_zoom |
The minimum zoom level for the layer. |
max_zoom |
The maximum zoom level for the layer. |
popup |
A column name containing information to display in a popup on click. Columns containing HTML will be parsed. |
tooltip |
A column name containing information to display in a tooltip on hover. Columns containing HTML will be parsed. |
hover_options |
A named list of options for highlighting features in the layer on hover. |
before_id |
The name of the layer that this layer appears "before", allowing you to insert layers below other layers in your basemap (e.g. labels). |
filter |
An optional filter expression to subset features in the layer. |
The modified map object with the new fill-extrusion layer added.
## Not run: library(mapgl) maplibre( style = maptiler_style("basic"), center = c(-74.0066, 40.7135), zoom = 15.5, pitch = 45, bearing = -17.6 ) |> add_vector_source( id = "openmaptiles", url = paste0( "https://api.maptiler.com/tiles/v3/tiles.json?key=", Sys.getenv("MAPTILER_API_KEY") ) ) |> add_fill_extrusion_layer( id = "3d-buildings", source = "openmaptiles", source_layer = "building", fill_extrusion_color = interpolate( column = "render_height", values = c(0, 200, 400), stops = c("lightgray", "royalblue", "lightblue") ), fill_extrusion_height = list( "interpolate", list("linear"), list("zoom"), 15, 0, 16, list("get", "render_height") ) ) ## End(Not run)## Not run: library(mapgl) maplibre( style = maptiler_style("basic"), center = c(-74.0066, 40.7135), zoom = 15.5, pitch = 45, bearing = -17.6 ) |> add_vector_source( id = "openmaptiles", url = paste0( "https://api.maptiler.com/tiles/v3/tiles.json?key=", Sys.getenv("MAPTILER_API_KEY") ) ) |> add_fill_extrusion_layer( id = "3d-buildings", source = "openmaptiles", source_layer = "building", fill_extrusion_color = interpolate( column = "render_height", values = c(0, 200, 400), stops = c("lightgray", "royalblue", "lightblue") ), fill_extrusion_height = list( "interpolate", list("linear"), list("zoom"), 15, 0, 16, list("get", "render_height") ) ) ## End(Not run)
Add a fill layer to a map
add_fill_layer( map, id, source, source_layer = NULL, fill_antialias = TRUE, fill_color = NULL, fill_emissive_strength = NULL, fill_opacity = NULL, fill_outline_color = NULL, fill_pattern = NULL, fill_pattern_cross_fade = NULL, fill_sort_key = NULL, fill_translate = NULL, fill_translate_anchor = "map", fill_z_offset = NULL, visibility = "visible", slot = NULL, min_zoom = NULL, max_zoom = NULL, popup = NULL, tooltip = NULL, hover_options = NULL, before_id = NULL, filter = NULL )add_fill_layer( map, id, source, source_layer = NULL, fill_antialias = TRUE, fill_color = NULL, fill_emissive_strength = NULL, fill_opacity = NULL, fill_outline_color = NULL, fill_pattern = NULL, fill_pattern_cross_fade = NULL, fill_sort_key = NULL, fill_translate = NULL, fill_translate_anchor = "map", fill_z_offset = NULL, visibility = "visible", slot = NULL, min_zoom = NULL, max_zoom = NULL, popup = NULL, tooltip = NULL, hover_options = NULL, before_id = NULL, filter = NULL )
map |
A map object created by the |
id |
A unique ID for the layer. |
source |
The ID of the source, alternatively an sf object (which will be converted to a GeoJSON source) or a named list that specifies |
source_layer |
The source layer (for vector sources). |
fill_antialias |
Whether or not the fill should be antialiased. |
fill_color |
The color of the filled part of this layer. |
fill_emissive_strength |
Controls the intensity of light emitted on the source features. |
fill_opacity |
The opacity of the entire fill layer. |
fill_outline_color |
The outline color of the fill. |
fill_pattern |
Name of image in sprite to use for drawing image fills. |
fill_pattern_cross_fade |
Controls the transition progress between image variants of |
fill_sort_key |
Sorts features in ascending order based on this value. |
fill_translate |
The geometry's offset. Values are |
fill_translate_anchor |
Controls the frame of reference for |
fill_z_offset |
Specifies an uniform elevation in meters. |
visibility |
Whether this layer is displayed. |
slot |
An optional slot for layer order. |
min_zoom |
The minimum zoom level for the layer. |
max_zoom |
The maximum zoom level for the layer. |
popup |
A column name containing information to display in a popup on click. Columns containing HTML will be parsed. |
tooltip |
A column name containing information to display in a tooltip on hover. Columns containing HTML will be parsed. |
hover_options |
A named list of options for highlighting features in the layer on hover. |
before_id |
The name of the layer that this layer appears "before", allowing you to insert layers below other layers in your basemap (e.g. labels). |
filter |
An optional filter expression to subset features in the layer. |
The modified map object with the new fill layer added.
## Not run: library(tidycensus) fl_age <- get_acs( geography = "tract", variables = "B01002_001", state = "FL", year = 2022, geometry = TRUE ) mapboxgl() |> fit_bounds(fl_age, animate = FALSE) |> add_fill_layer( id = "fl_tracts", source = fl_age, fill_color = interpolate( column = "estimate", values = c(20, 80), stops = c("lightblue", "darkblue"), na_color = "lightgrey" ), fill_opacity = 0.5 ) ## End(Not run)## Not run: library(tidycensus) fl_age <- get_acs( geography = "tract", variables = "B01002_001", state = "FL", year = 2022, geometry = TRUE ) mapboxgl() |> fit_bounds(fl_age, animate = FALSE) |> add_fill_layer( id = "fl_tracts", source = fl_age, fill_color = interpolate( column = "estimate", values = c(20, 80), stops = c("lightblue", "darkblue"), na_color = "lightgrey" ), fill_opacity = 0.5 ) ## End(Not run)
Adds a FlowmapGL layer for visualizing origin-destination flows between point locations.
add_flowmap( map, id, locations, flows, flow_color_scheme = "Teal", flow_opacity = 1, flow_dark_mode = "auto", flow_blend = "auto", flow_fade_amount = 50, flow_highlight_color = "#ff9b29", flow_locations_enabled = TRUE, flow_location_totals_enabled = TRUE, flow_location_labels_enabled = FALSE, flow_lines_rendering_mode = c("straight", "animated-straight", "curved"), flow_line_thickness_scale = 1, flow_line_curviness = 1, flow_clustering_enabled = TRUE, flow_clustering_auto = TRUE, flow_clustering_level = NULL, flow_fade_enabled = TRUE, flow_fade_opacity_enabled = FALSE, flow_adaptive_scales_enabled = TRUE, flow_temporal_scale_domain = c("selected", "all"), flow_max_top_flows_display_num = 5000, flow_endpoints_in_viewport_mode = c("any", "both"), flow_time_column = NULL, flow_selected_time_range = NULL, flow_selected_locations = NULL, flow_location_filter_mode = c("ALL", "INCOMING", "OUTGOING", "BETWEEN"), tooltip = TRUE, popup = FALSE, tooltip_style = c("floating", "anchored"), popup_style = c("floating", "anchored"), tooltip_theme = c("auto", "light", "dark"), popup_theme = c("auto", "light", "dark"), tooltip_options = list(), popup_options = list(), visibility = c("visible", "none"), before_id = NULL, slot = NULL )add_flowmap( map, id, locations, flows, flow_color_scheme = "Teal", flow_opacity = 1, flow_dark_mode = "auto", flow_blend = "auto", flow_fade_amount = 50, flow_highlight_color = "#ff9b29", flow_locations_enabled = TRUE, flow_location_totals_enabled = TRUE, flow_location_labels_enabled = FALSE, flow_lines_rendering_mode = c("straight", "animated-straight", "curved"), flow_line_thickness_scale = 1, flow_line_curviness = 1, flow_clustering_enabled = TRUE, flow_clustering_auto = TRUE, flow_clustering_level = NULL, flow_fade_enabled = TRUE, flow_fade_opacity_enabled = FALSE, flow_adaptive_scales_enabled = TRUE, flow_temporal_scale_domain = c("selected", "all"), flow_max_top_flows_display_num = 5000, flow_endpoints_in_viewport_mode = c("any", "both"), flow_time_column = NULL, flow_selected_time_range = NULL, flow_selected_locations = NULL, flow_location_filter_mode = c("ALL", "INCOMING", "OUTGOING", "BETWEEN"), tooltip = TRUE, popup = FALSE, tooltip_style = c("floating", "anchored"), popup_style = c("floating", "anchored"), tooltip_theme = c("auto", "light", "dark"), popup_theme = c("auto", "light", "dark"), tooltip_options = list(), popup_options = list(), visibility = c("visible", "none"), before_id = NULL, slot = NULL )
map |
A map object created by |
id |
A unique layer ID. |
locations |
A data frame or |
flows |
A data frame with |
flow_color_scheme |
FlowMapGL preset color scheme name, a character
vector of at least two CSS colors, or a |
flow_opacity |
Layer opacity between 0 and 1. |
flow_dark_mode |
Logical ( |
flow_blend |
Logical ( Valid modes are: Recommendations:
If |
flow_fade_amount |
Controls how much lower-magnitude flows fade compared to higher ones. Range: 0-100. |
flow_highlight_color |
Color used for highlighting hovered elements. |
flow_locations_enabled |
Whether to show location circles. |
flow_location_totals_enabled |
Whether to show incoming/outgoing totals as concentric circles at each location. |
flow_location_labels_enabled |
Whether to show text labels at locations. |
flow_lines_rendering_mode |
Controls how flow lines are rendered: |
flow_line_thickness_scale |
Multiplier for flow line thickness. |
flow_line_curviness |
Multiplier for flow line curviness (only used when |
flow_clustering_enabled |
Whether to cluster nearby locations when zoomed out. |
flow_clustering_auto |
Whether to automatically adjust clustering level based on zoom. |
flow_clustering_level |
Fixed clustering zoom level. Only used when |
flow_fade_enabled |
Whether to apply color fading to lower-magnitude flows. |
flow_fade_opacity_enabled |
Whether to also fade opacity for lower-magnitude flows. |
flow_adaptive_scales_enabled |
Whether to adapt flow thickness and color scales to the current viewport. This controls the spatial scale domain while panning and zooming. |
flow_temporal_scale_domain |
For temporal flowmaps, whether flow
thickness and color scales use only the currently selected time range
( |
flow_max_top_flows_display_num |
Maximum number of flows to display. |
flow_endpoints_in_viewport_mode |
Controls when a flow is considered visible based on endpoint locations: |
flow_time_column |
Optional column name in |
flow_selected_time_range |
Optional vector of two dates (or strings) for initial time filtering. |
flow_selected_locations |
Optional vector of location IDs to select. |
flow_location_filter_mode |
Optional location filter mode: |
tooltip |
Tooltip configuration. Use |
popup |
Popup configuration. Use |
tooltip_style |
Tooltip rendering style: |
popup_style |
Popup rendering style: |
tooltip_theme |
Tooltip theme. |
popup_theme |
Popup theme. |
tooltip_options |
A named list of renderer-specific tooltip options. |
popup_options |
A named list of renderer-specific popup options. |
visibility |
Whether the layer is initially |
before_id |
Optional map layer ID to render before. |
slot |
Optional Mapbox Standard slot. |
Mapbox and MapLibre layer paint arguments such as fill_color,
circle_color, and line_color require a scalar CSS color or a style
expression. Use interpolate_palette(...)$expression for data-driven layer
color ramps. FlowMapGL's flow_color_scheme accepts a preset name such as
"Teal", a plain color ramp such as c("red", "white", "blue"), or an
interpolate_palette(...) scale object.
Flow scale domains have separate spatial and temporal controls.
flow_adaptive_scales_enabled = TRUE rescales flow thickness and color for
the current viewport; FALSE keeps the scale tied to the broader map extent.
For temporal flowmaps, flow_temporal_scale_domain = "selected" rescales
within the selected time-control interval, while "all" keeps the scale
comparable across the full time extent.
The modified map object with the flowmap layer added.
# Create a flowmap centered on Montréal using the bundled datasets maplibre( style = carto_style("dark-matter"), center = c(-73.58, 45.50), zoom = 11, projection = "mercator" ) |> add_flowmap( id = "bixi-rides", locations = bixi_locations, flows = bixi_flows, flow_time_column = "time", flow_color_scheme = "Teal", flow_dark_mode = TRUE ) |> add_time_control( data = bixi_flows, time_column = "time", time_interval = "hour", title = "BIXI Montréal Rides" )# Create a flowmap centered on Montréal using the bundled datasets maplibre( style = carto_style("dark-matter"), center = c(-73.58, 45.50), zoom = 11, projection = "mercator" ) |> add_flowmap( id = "bixi-rides", locations = bixi_locations, flows = bixi_flows, flow_time_column = "time", flow_color_scheme = "Teal", flow_dark_mode = TRUE ) |> add_time_control( data = bixi_flows, time_column = "time", time_interval = "hour", title = "BIXI Montréal Rides" )
Add a fullscreen control to a map
add_fullscreen_control(map, position = "top-right")add_fullscreen_control(map, position = "top-right")
map |
A map object created by the |
position |
A string specifying the position of the fullscreen control. One of "top-right", "top-left", "bottom-right", or "bottom-left". |
The modified map object with the fullscreen control added.
## Not run: library(mapgl) maplibre( style = maptiler_style("streets"), center = c(11.255, 43.77), zoom = 13 ) |> add_fullscreen_control(position = "top-right") ## End(Not run)## Not run: library(mapgl) maplibre( style = maptiler_style("streets"), center = c(11.255, 43.77), zoom = 13 ) |> add_fullscreen_control(position = "top-right") ## End(Not run)
This function adds a Geocoder search bar to a Mapbox GL or MapLibre GL map.
By default, a marker will be added at the selected location and the map will
fly to that location. The results of the geocode are accessible in a Shiny
session at input$MAPID_geocoder$result, where MAPID is the name of your map.
add_geocoder_control( map, position = "top-right", placeholder = "Search", collapsed = FALSE, provider = NULL, maptiler_api_key = NULL, ... )add_geocoder_control( map, position = "top-right", placeholder = "Search", collapsed = FALSE, provider = NULL, maptiler_api_key = NULL, ... )
map |
A map object created by the |
position |
The position of the control. Can be one of "top-left", "top-right", "bottom-left", or "bottom-right". Default is "top-right". |
placeholder |
A string to use as placeholder text for the search bar. Default is "Search". |
collapsed |
Whether the control should be collapsed until hovered or clicked. Default is FALSE. |
provider |
The geocoding provider to use for MapLibre maps. Either "osm" for OpenStreetMap/Nominatim or "maptiler" for MapTiler geocoding. If NULL (default), MapLibre maps will use "osm". Mapbox maps will always use the Mapbox geocoder, regardless of this parameter. |
maptiler_api_key |
Your MapTiler API key (required when provider is "maptiler" for MapLibre maps). Can also be set with |
... |
Additional parameters to pass to the Geocoder. |
The modified map object with the geocoder control added.
## Not run: library(mapgl) mapboxgl() |> add_geocoder_control(position = "top-left", placeholder = "Enter an address") maplibre() |> add_geocoder_control(position = "top-right", placeholder = "Search location") # Using MapTiler geocoder maplibre() |> add_geocoder_control(provider = "maptiler", maptiler_api_key = "YOUR_API_KEY") ## End(Not run)## Not run: library(mapgl) mapboxgl() |> add_geocoder_control(position = "top-left", placeholder = "Enter an address") maplibre() |> add_geocoder_control(position = "top-right", placeholder = "Search location") # Using MapTiler geocoder maplibre() |> add_geocoder_control(provider = "maptiler", maptiler_api_key = "YOUR_API_KEY") ## End(Not run)
This function adds a Geolocate control to a Mapbox GL or MapLibre GL map. The geolocate control allows users to track their current location on the map.
add_geolocate_control( map, position = "top-right", track_user = FALSE, show_accuracy_circle = TRUE, show_user_location = TRUE, show_user_heading = FALSE, fit_bounds_options = list(maxZoom = 15), position_options = list(enableHighAccuracy = FALSE, timeout = 6000) )add_geolocate_control( map, position = "top-right", track_user = FALSE, show_accuracy_circle = TRUE, show_user_location = TRUE, show_user_heading = FALSE, fit_bounds_options = list(maxZoom = 15), position_options = list(enableHighAccuracy = FALSE, timeout = 6000) )
map |
A map object created by the |
position |
The position of the control. Can be one of "top-left", "top-right", "bottom-left", or "bottom-right". Default is "top-right". |
track_user |
Whether to actively track the user's location. If TRUE, the map will continuously update as the user moves. Default is FALSE. |
show_accuracy_circle |
Whether to show a circle indicating the accuracy of the location. Default is TRUE. |
show_user_location |
Whether to show a dot at the user's location. Default is TRUE. |
show_user_heading |
Whether to show an arrow indicating the device's heading when tracking location. Only works when track_user is TRUE. Default is FALSE. |
fit_bounds_options |
A list of options for fitting bounds when panning to the user's location. Default maxZoom is 15. |
position_options |
A list of Geolocation API position options. Default has enableHighAccuracy=FALSE and timeout=6000. |
The modified map object with the geolocate control added.
## Not run: library(mapgl) mapboxgl() |> add_geolocate_control( position = "top-right", track_user = TRUE, show_user_heading = TRUE ) ## End(Not run)## Not run: library(mapgl) mapboxgl() |> add_geolocate_control( position = "top-right", track_user = TRUE, show_user_heading = TRUE ) ## End(Not run)
This function adds a globe control to a MapLibre GL map that allows toggling between "mercator" and "globe" projections with a single click.
add_globe_control(map, position = "top-right")add_globe_control(map, position = "top-right")
map |
A map object created by the |
position |
The position of the control. Can be one of "top-left", "top-right", "bottom-left", or "bottom-right". Default is "top-right". |
The modified map object with the globe control added.
## Not run: library(mapgl) maplibre() |> add_globe_control(position = "top-right") ## End(Not run)## Not run: library(mapgl) maplibre() |> add_globe_control(position = "top-right") ## End(Not run)
This function adds a globe minimap control to a Mapbox GL or Maplibre map.
add_globe_minimap( map, position = "bottom-right", globe_size = 82, land_color = "white", water_color = "rgba(30 40 70/60%)", marker_color = "#ff2233", marker_size = 1 )add_globe_minimap( map, position = "bottom-right", globe_size = 82, land_color = "white", water_color = "rgba(30 40 70/60%)", marker_color = "#ff2233", marker_size = 1 )
map |
A |
position |
A string specifying the position of the minimap. |
globe_size |
Number of pixels for the diameter of the globe. Default is 82. |
land_color |
HTML color to use for land areas on the globe. Default is 'white'. |
water_color |
HTML color to use for water areas on the globe. Default is 'rgba(30 40 70/60%)'. |
marker_color |
HTML color to use for the center point marker. Default is '#ff2233'. |
marker_size |
Scale ratio for the center point marker. Default is 1. |
The modified map object with the globe minimap added.
## Not run: library(mapgl) m <- mapboxgl() %>% add_globe_minimap() m <- maplibre() %>% add_globe_minimap() ## End(Not run)## Not run: library(mapgl) m <- mapboxgl() %>% add_globe_minimap() m <- maplibre() %>% add_globe_minimap() ## End(Not run)
Add a hexagon source from the H3 geospatial indexing system.
add_h3j_source(map, id, url)add_h3j_source(map, id, url)
map |
A map object created by the |
id |
A unique ID for the source. |
url |
A URL pointing to the vector tile source. |
https://h3geo.org, https://github.com/INSPIDE/h3j-h3t
url = "https://inspide.github.io/h3j-h3t/examples/h3j/sample.h3j" maplibre(center=c(-3.704, 40.417), zoom=15, pitch=30) |> add_h3j_source("h3j_testsource", url = url ) |> add_fill_extrusion_layer( id = "h3j_testlayer", source = "h3j_testsource", fill_extrusion_color = interpolate( column = "value", values = c(0, 21.864), stops = c("#430254", "#f83c70") ), fill_extrusion_height = list( "interpolate", list("linear"), list("zoom"), 14, 0, 15.05, list("*", 10, list("get", "value")) ), fill_extrusion_opacity = 0.7 )url = "https://inspide.github.io/h3j-h3t/examples/h3j/sample.h3j" maplibre(center=c(-3.704, 40.417), zoom=15, pitch=30) |> add_h3j_source("h3j_testsource", url = url ) |> add_fill_extrusion_layer( id = "h3j_testlayer", source = "h3j_testsource", fill_extrusion_color = interpolate( column = "value", values = c(0, 21.864), stops = c("#430254", "#f83c70") ), fill_extrusion_height = list( "interpolate", list("linear"), list("zoom"), 14, 0, 15.05, list("*", 10, list("get", "value")) ), fill_extrusion_opacity = 0.7 )
Add a heatmap layer to a Mapbox GL map
add_heatmap_layer( map, id, source, source_layer = NULL, heatmap_color = NULL, heatmap_intensity = NULL, heatmap_opacity = NULL, heatmap_radius = NULL, heatmap_weight = NULL, visibility = "visible", slot = NULL, min_zoom = NULL, max_zoom = NULL, before_id = NULL, filter = NULL )add_heatmap_layer( map, id, source, source_layer = NULL, heatmap_color = NULL, heatmap_intensity = NULL, heatmap_opacity = NULL, heatmap_radius = NULL, heatmap_weight = NULL, visibility = "visible", slot = NULL, min_zoom = NULL, max_zoom = NULL, before_id = NULL, filter = NULL )
map |
A map object created by the |
id |
A unique ID for the layer. |
source |
The ID of the source, alternatively an sf object (which will be converted to a GeoJSON source) or a named list that specifies |
source_layer |
The source layer (for vector sources). |
heatmap_color |
The color of the heatmap points. |
heatmap_intensity |
The intensity of the heatmap points. |
heatmap_opacity |
The opacity of the heatmap layer. |
heatmap_radius |
The radius of influence of each individual heatmap point. |
heatmap_weight |
The weight of each individual heatmap point. |
visibility |
Whether this layer is displayed. |
slot |
An optional slot for layer order. |
min_zoom |
The minimum zoom level for the layer. |
max_zoom |
The maximum zoom level for the layer. |
before_id |
The name of the layer that this layer appears "before", allowing you to insert layers below other layers in your basemap (e.g. labels). |
filter |
An optional filter expression to subset features in the layer. |
The modified map object with the new heatmap layer added.
## Not run: library(mapgl) mapboxgl( style = mapbox_style("dark"), center = c(-120, 50), zoom = 2 ) |> add_heatmap_layer( id = "earthquakes-heat", source = list( type = "geojson", data = "https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson" ), heatmap_weight = interpolate( column = "mag", values = c(0, 6), stops = c(0, 1) ), heatmap_intensity = interpolate( property = "zoom", values = c(0, 9), stops = c(1, 3) ), heatmap_color = interpolate( property = "heatmap-density", values = seq(0, 1, 0.2), stops = c( "rgba(33,102,172,0)", "rgb(103,169,207)", "rgb(209,229,240)", "rgb(253,219,199)", "rgb(239,138,98)", "rgb(178,24,43)" ) ), heatmap_opacity = 0.7 ) ## End(Not run)## Not run: library(mapgl) mapboxgl( style = mapbox_style("dark"), center = c(-120, 50), zoom = 2 ) |> add_heatmap_layer( id = "earthquakes-heat", source = list( type = "geojson", data = "https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson" ), heatmap_weight = interpolate( column = "mag", values = c(0, 6), stops = c(0, 1) ), heatmap_intensity = interpolate( property = "zoom", values = c(0, 9), stops = c(1, 3) ), heatmap_color = interpolate( property = "heatmap-density", values = seq(0, 1, 0.2), stops = c( "rgba(33,102,172,0)", "rgb(103,169,207)", "rgb(209,229,240)", "rgb(253,219,199)", "rgb(239,138,98)", "rgb(178,24,43)" ) ), heatmap_opacity = 0.7 ) ## End(Not run)
This function adds an image to the map's style. The image can be used with
icon-image, background-pattern, fill-pattern, or line-pattern.
It can also be used with a style list, such as one created by
basemap_style(), before the style is supplied to maplibre() or
mapboxgl().
add_image( map, id, url, content = NULL, pixel_ratio = 1, sdf = FALSE, stretch_x = NULL, stretch_y = NULL )add_image( map, id, url, content = NULL, pixel_ratio = 1, sdf = FALSE, stretch_x = NULL, stretch_y = NULL )
map |
A map object created by the |
id |
A string specifying the ID of the image. |
url |
A string specifying the URL of the image to be loaded or a path to a local image file. Must be PNG or JPEG format. |
content |
A vector of four numbers |
pixel_ratio |
A number specifying the ratio of pixels in the image to physical pixels on the screen. |
sdf |
A logical value indicating whether the image should be interpreted as an SDF image. |
stretch_x |
A list of number pairs defining the part(s) of the image that can be stretched horizontally. |
stretch_y |
A list of number pairs defining the part(s) of the image that can be stretched vertically. |
The modified map object or style list with the image added.
## Not run: library(mapgl) # Path to your local image file OR a URL to a remote image file # that is not blocked by CORS restrictions image_path <- "/path/to/your/image.png" pts <- tigris::landmarks("DE")[1:100, ] maplibre(bounds = pts) |> add_image("local_icon", image_path) |> add_symbol_layer( id = "local_icons", source = pts, icon_image = "local_icon", icon_size = 0.5, icon_allow_overlap = TRUE ) ## End(Not run)## Not run: library(mapgl) # Path to your local image file OR a URL to a remote image file # that is not blocked by CORS restrictions image_path <- "/path/to/your/image.png" pts <- tigris::landmarks("DE")[1:100, ] maplibre(bounds = pts) |> add_image("local_icon", image_path) |> add_symbol_layer( id = "local_icons", source = pts, icon_image = "local_icon", icon_size = 0.5, icon_allow_overlap = TRUE ) ## End(Not run)
Add an image source to a Mapbox GL or Maplibre GL map
add_image_source( map, id, url = NULL, data = NULL, coordinates = NULL, colors = NULL )add_image_source( map, id, url = NULL, data = NULL, coordinates = NULL, colors = NULL )
map |
A map object created by the |
id |
A unique ID for the source. |
url |
A URL pointing to the image source. |
data |
A |
coordinates |
A list of coordinates specifying the image corners in clockwise order: top left, top right, bottom right, bottom left. For |
colors |
A vector of colors to use for the raster image. |
The modified map object with the new source added.
In many cases, you will use add_layer() internal to other layer-specific functions in mapgl. Advanced users will want to use add_layer() for more fine-grained control over the appearance of their layers.
add_layer( map, id, type = "fill", source, source_layer = NULL, paint = list(), layout = list(), slot = NULL, min_zoom = NULL, max_zoom = NULL, popup = NULL, tooltip = NULL, hover_options = NULL, before_id = NULL, filter = NULL )add_layer( map, id, type = "fill", source, source_layer = NULL, paint = list(), layout = list(), slot = NULL, min_zoom = NULL, max_zoom = NULL, popup = NULL, tooltip = NULL, hover_options = NULL, before_id = NULL, filter = NULL )
map |
A map object created by the |
id |
A unique ID for the layer. |
type |
The type of the layer (e.g., "fill", "line", "circle"). |
source |
The ID of the source, alternatively an sf object (which will be converted to a GeoJSON source) or a named list that specifies |
source_layer |
The source layer (for vector sources). |
paint |
A list of paint properties for the layer. |
layout |
A list of layout properties for the layer. |
slot |
An optional slot for layer order. |
min_zoom |
The minimum zoom level for the layer. |
max_zoom |
The maximum zoom level for the layer. |
popup |
A column name containing information to display in a popup on click. Columns containing HTML will be parsed. |
tooltip |
A column name containing information to display in a tooltip on hover. Columns containing HTML will be parsed. |
hover_options |
A named list of options for highlighting features in the layer on hover. |
before_id |
The name of the layer that this layer appears "before", allowing you to insert layers below other layers in your basemap (e.g. labels). |
filter |
An optional filter expression to subset features in the layer. |
The modified map object with the new layer added.
## Not run: # Load necessary libraries library(mapgl) library(tigris) # Load geojson data for North Carolina tracts nc_tracts <- tracts(state = "NC", cb = TRUE) # Create a Mapbox GL map map <- mapboxgl( style = mapbox_style("light"), center = c(-79.0193, 35.7596), zoom = 7 ) # Add a source and fill layer for North Carolina tracts map %>% add_source( id = "nc-tracts", data = nc_tracts ) %>% add_layer( id = "nc-layer", type = "fill", source = "nc-tracts", paint = list( "fill-color" = "#888888", "fill-opacity" = 0.4 ) ) ## End(Not run)## Not run: # Load necessary libraries library(mapgl) library(tigris) # Load geojson data for North Carolina tracts nc_tracts <- tracts(state = "NC", cb = TRUE) # Create a Mapbox GL map map <- mapboxgl( style = mapbox_style("light"), center = c(-79.0193, 35.7596), zoom = 7 ) # Add a source and fill layer for North Carolina tracts map %>% add_source( id = "nc-tracts", data = nc_tracts ) %>% add_layer( id = "nc-layer", type = "fill", source = "nc-tracts", paint = list( "fill-color" = "#888888", "fill-opacity" = 0.4 ) ) ## End(Not run)
This function adds an interactive live customization widget (using lil-gui) to the map. It allows users to customize paint and layout properties of map layers in real-time.
add_layer_tuner( map, layers = "all", show_all_args = FALSE, title = NULL, position = "top-left", width = 245, height = NULL, collapsed = FALSE )add_layer_tuner( map, layers = "all", show_all_args = FALSE, title = NULL, position = "top-left", width = 245, height = NULL, collapsed = FALSE )
map |
A |
layers |
A character vector of layer IDs to include in the tuner, or |
show_all_args |
A logical value. If |
title |
Optional title for the tuner panel. Defaults to the built-in layer tuner title. |
position |
Initial position of the tuner panel. One of |
width |
Initial tuner panel width. Numeric values are interpreted as
pixels; character values are passed through as CSS lengths. Defaults to
|
height |
Optional initial tuner panel height. Numeric values are
interpreted as pixels; character values are passed through as CSS lengths.
Defaults to |
collapsed |
Logical value indicating whether the tuner panel should be
collapsed initially. Defaults to |
The modified map object with the layer tuner added.
# Create a flowmap centered on Montréal using the bundled datasets and add a layer tuner maplibre( style = carto_style("dark-matter"), center = c(-73.58, 45.50), zoom = 11, projection = "mercator" ) |> add_flowmap( id = "bixi-rides", locations = bixi_locations, flows = bixi_flows, flow_time_column = "time", flow_color_scheme = "Teal", flow_dark_mode = TRUE ) |> add_layer_tuner(position = "top-right", width = 320)# Create a flowmap centered on Montréal using the bundled datasets and add a layer tuner maplibre( style = carto_style("dark-matter"), center = c(-73.58, 45.50), zoom = 11, projection = "mercator" ) |> add_flowmap( id = "bixi-rides", locations = bixi_locations, flows = bixi_flows, flow_time_column = "time", flow_color_scheme = "Teal", flow_dark_mode = TRUE ) |> add_layer_tuner(position = "top-right", width = 320)
Add a layers control to the map
add_layers_control( map, position = "top-left", layers = NULL, collapsible = TRUE, use_icon = TRUE, background_color = NULL, active_color = NULL, hover_color = NULL, active_text_color = NULL, inactive_text_color = NULL, margin_top = NULL, margin_right = NULL, margin_bottom = NULL, margin_left = NULL )add_layers_control( map, position = "top-left", layers = NULL, collapsible = TRUE, use_icon = TRUE, background_color = NULL, active_color = NULL, hover_color = NULL, active_text_color = NULL, inactive_text_color = NULL, margin_top = NULL, margin_right = NULL, margin_bottom = NULL, margin_left = NULL )
map |
A map object. |
position |
The position of the control on the map (one of "top-left", "top-right", "bottom-left", "bottom-right"). |
layers |
Either a character vector of layer IDs to include in the control, a named list/vector where names are labels and values are layer IDs, or a named list where values can be vectors to group multiple layers together. If NULL, all layers will be included. |
collapsible |
Whether the control should be collapsible. |
use_icon |
Whether to use a stacked layers icon instead of the "Layers" text when collapsed. Only applies when collapsible = TRUE. |
background_color |
The background color for the layers control; this will be the color used for inactive layer items. |
active_color |
The background color for active layer items. |
hover_color |
The background color for layer items when hovered. |
active_text_color |
The text color for active layer items. |
inactive_text_color |
The text color for inactive layer items. |
margin_top |
Custom top margin in pixels, allowing for fine control over control positioning to avoid overlaps. Default is NULL (uses standard positioning). |
margin_right |
Custom right margin in pixels. Default is NULL. |
margin_bottom |
Custom bottom margin in pixels. Default is NULL. |
margin_left |
Custom left margin in pixels. Default is NULL. |
The modified map object with the layers control added.
## Not run: library(tigris) options(tigris_use_cache = TRUE) rds <- roads("TX", "Tarrant") tr <- tracts("TX", "Tarrant", cb = TRUE) cty <- counties("TX", cb = TRUE) maplibre() |> fit_bounds(rds) |> add_fill_layer( id = "Census tracts", source = tr, fill_color = "purple", fill_opacity = 0.6 ) |> add_line_layer( "Local roads", source = rds, line_color = "pink" ) |> add_layers_control( position = "top-left", background_color = "#ffffff", active_color = "#4a90e2" ) # With custom labels maplibre() |> add_fill_layer(id = "tract-fill", source = tr) |> add_line_layer(id = "tract-line", source = tr) |> add_layers_control( layers = list( "Census Tracts" = "tract-fill", "Tract Borders" = "tract-line" ) ) # Group multiple layers together maplibre(bounds = cty) |> add_fill_layer(id = "county-fill", source = cty, fill_opacity = 0.3) |> add_line_layer( id = "county-outline", source = cty, line_color = "yellow", line_width = 3 ) |> add_line_layer( id = "roads-layer", source = rds, line_color = "blue" ) |> add_layers_control( layers = list( "Counties" = c("county-fill", "county-outline"), "Roads" = "roads-layer" ) ) ## End(Not run)## Not run: library(tigris) options(tigris_use_cache = TRUE) rds <- roads("TX", "Tarrant") tr <- tracts("TX", "Tarrant", cb = TRUE) cty <- counties("TX", cb = TRUE) maplibre() |> fit_bounds(rds) |> add_fill_layer( id = "Census tracts", source = tr, fill_color = "purple", fill_opacity = 0.6 ) |> add_line_layer( "Local roads", source = rds, line_color = "pink" ) |> add_layers_control( position = "top-left", background_color = "#ffffff", active_color = "#4a90e2" ) # With custom labels maplibre() |> add_fill_layer(id = "tract-fill", source = tr) |> add_line_layer(id = "tract-line", source = tr) |> add_layers_control( layers = list( "Census Tracts" = "tract-fill", "Tract Borders" = "tract-line" ) ) # Group multiple layers together maplibre(bounds = cty) |> add_fill_layer(id = "county-fill", source = cty, fill_opacity = 0.3) |> add_line_layer( id = "county-outline", source = cty, line_color = "yellow", line_width = 3 ) |> add_line_layer( id = "roads-layer", source = rds, line_color = "blue" ) |> add_layers_control( layers = list( "Counties" = c("county-fill", "county-outline"), "Roads" = "roads-layer" ) ) ## End(Not run)
Add a line layer to a map
add_line_layer( map, id, source, source_layer = NULL, line_blur = NULL, line_cap = NULL, line_color = NULL, line_dasharray = NULL, line_elevation_ground_scale = NULL, line_elevation_reference = NULL, line_emissive_strength = NULL, line_gap_width = NULL, line_gradient = NULL, line_join = NULL, line_miter_limit = NULL, line_occlusion_opacity = NULL, line_offset = NULL, line_opacity = NULL, line_pattern = NULL, line_pattern_cross_fade = NULL, line_round_limit = NULL, line_sort_key = NULL, line_translate = NULL, line_translate_anchor = "map", line_trim_color = NULL, line_trim_fade_range = NULL, line_trim_offset = NULL, line_width = NULL, line_z_offset = NULL, visibility = "visible", slot = NULL, min_zoom = NULL, max_zoom = NULL, popup = NULL, tooltip = NULL, hover_options = NULL, before_id = NULL, filter = NULL )add_line_layer( map, id, source, source_layer = NULL, line_blur = NULL, line_cap = NULL, line_color = NULL, line_dasharray = NULL, line_elevation_ground_scale = NULL, line_elevation_reference = NULL, line_emissive_strength = NULL, line_gap_width = NULL, line_gradient = NULL, line_join = NULL, line_miter_limit = NULL, line_occlusion_opacity = NULL, line_offset = NULL, line_opacity = NULL, line_pattern = NULL, line_pattern_cross_fade = NULL, line_round_limit = NULL, line_sort_key = NULL, line_translate = NULL, line_translate_anchor = "map", line_trim_color = NULL, line_trim_fade_range = NULL, line_trim_offset = NULL, line_width = NULL, line_z_offset = NULL, visibility = "visible", slot = NULL, min_zoom = NULL, max_zoom = NULL, popup = NULL, tooltip = NULL, hover_options = NULL, before_id = NULL, filter = NULL )
map |
A map object created by the |
id |
A unique ID for the layer. |
source |
The ID of the source, alternatively an sf object (which will be
converted to a GeoJSON source) or a named list that specifies |
source_layer |
The source layer (for vector sources). |
line_blur |
Amount to blur the line, in pixels. |
line_cap |
The display of line endings. One of "butt", "round", "square". |
line_color |
The color with which the line will be drawn. |
line_dasharray |
Specifies the lengths of the alternating dashes and gaps that form the dash pattern. |
line_elevation_ground_scale |
Controls how much the elevation of lines
scales with terrain exaggeration when |
line_elevation_reference |
Selects the base of line elevation. One of
|
line_emissive_strength |
Controls the intensity of light emitted on the source features. |
line_gap_width |
Draws a line casing outside of a line's actual path. Value indicates the width of the inner gap. |
line_gradient |
A gradient used to color a line feature at various distances along its length. |
line_join |
The display of lines when joining. |
line_miter_limit |
Used to automatically convert miter joins to bevel joins for sharp angles. |
line_occlusion_opacity |
Opacity multiplier of the line part that is occluded by 3D objects. |
line_offset |
The line's offset. |
line_opacity |
The opacity at which the line will be drawn. |
line_pattern |
Name of image in sprite to use for drawing image lines. |
line_pattern_cross_fade |
Controls the transition progress between image variants of |
line_round_limit |
Used to automatically convert round joins to miter joins for shallow angles. |
line_sort_key |
Sorts features in ascending order based on this value. |
line_translate |
The geometry's offset. Values are |
line_translate_anchor |
Controls the frame of reference for |
line_trim_color |
The color to be used for rendering the trimmed line section. |
line_trim_fade_range |
The fade range for the trim-start and trim-end points. |
line_trim_offset |
The line part between |
line_width |
Stroke thickness. |
line_z_offset |
Vertical offset from ground, in meters. |
visibility |
Whether this layer is displayed. |
slot |
An optional slot for layer order. |
min_zoom |
The minimum zoom level for the layer. |
max_zoom |
The maximum zoom level for the layer. |
popup |
A column name containing information to display in a popup on click. Columns containing HTML will be parsed. |
tooltip |
A column name containing information to display in a tooltip on hover. Columns containing HTML will be parsed. |
hover_options |
A named list of options for highlighting features in the layer on hover. |
before_id |
The name of the layer that this layer appears "before", allowing you to insert layers below other layers in your basemap (e.g. labels) |
filter |
An optional filter expression to subset features in the layer. |
The modified map object with the new line layer added.
## Not run: library(mapgl) library(tigris) loving_roads <- roads("TX", "Loving") maplibre(style = maptiler_style("backdrop")) |> fit_bounds(loving_roads) |> add_line_layer( id = "tracks", source = loving_roads, line_color = "navy", line_opacity = 0.7 ) ## End(Not run)## Not run: library(mapgl) library(tigris) loving_roads <- roads("TX", "Loving") maplibre(style = maptiler_style("backdrop")) |> fit_bounds(loving_roads) |> add_line_layer( id = "tracks", source = loving_roads, line_color = "navy", line_opacity = 0.7 ) ## End(Not run)
Add markers to a Mapbox GL or Maplibre GL map
add_markers( map, data, color = "red", rotation = 0, popup = NULL, marker_id = NULL, draggable = FALSE, ... )add_markers( map, data, color = "red", rotation = 0, popup = NULL, marker_id = NULL, draggable = FALSE, ... )
map |
A map object created by the |
data |
A length-2 numeric vector of coordinates, a list of length-2 numeric vectors, or an |
color |
The color of the marker (default is "red"). |
rotation |
The rotation of the marker (default is 0). |
popup |
A column name for popups (if data is an |
marker_id |
A unique ID for the marker. For lists, names will be inherited from the list names. For |
draggable |
A boolean indicating if the marker should be draggable (default is FALSE). |
... |
Additional options passed to the marker. |
The modified map object with the markers added.
## Not run: library(mapgl) library(sf) # Create a map object map <- mapboxgl( style = mapbox_style("streets"), center = c(-74.006, 40.7128), zoom = 10 ) # Add a single draggable marker with an ID map <- add_markers( map, c(-74.006, 40.7128), color = "blue", rotation = 45, popup = "A marker", draggable = TRUE, marker_id = "marker1" ) # Add multiple markers from a named list of coordinates coords_list <- list(marker2 = c(-74.006, 40.7128), marker3 = c(-73.935242, 40.730610)) map <- add_markers( map, coords_list, color = "green", popup = "Multiple markers", draggable = TRUE ) # Create an sf POINT object points_sf <- st_as_sf(data.frame( id = c("marker4", "marker5"), lon = c(-74.006, -73.935242), lat = c(40.7128, 40.730610) ), coords = c("lon", "lat"), crs = 4326) points_sf$popup <- c("Point 1", "Point 2") # Add multiple markers from an sf object with IDs from a column map <- add_markers( map, points_sf, color = "red", popup = "popup", draggable = TRUE, marker_id = "id" ) ## End(Not run)## Not run: library(mapgl) library(sf) # Create a map object map <- mapboxgl( style = mapbox_style("streets"), center = c(-74.006, 40.7128), zoom = 10 ) # Add a single draggable marker with an ID map <- add_markers( map, c(-74.006, 40.7128), color = "blue", rotation = 45, popup = "A marker", draggable = TRUE, marker_id = "marker1" ) # Add multiple markers from a named list of coordinates coords_list <- list(marker2 = c(-74.006, 40.7128), marker3 = c(-73.935242, 40.730610)) map <- add_markers( map, coords_list, color = "green", popup = "Multiple markers", draggable = TRUE ) # Create an sf POINT object points_sf <- st_as_sf(data.frame( id = c("marker4", "marker5"), lon = c(-74.006, -73.935242), lat = c(40.7128, 40.730610) ), coords = c("lon", "lat"), crs = 4326) points_sf$popup <- c("Point 1", "Point 2") # Add multiple markers from an sf object with IDs from a column map <- add_markers( map, points_sf, color = "red", popup = "popup", draggable = TRUE, marker_id = "id" ) ## End(Not run)
Add a PMTiles source to a Mapbox GL or Maplibre GL map
add_pmtiles_source( map, id, url, source_type = "vector", maxzoom = 22, tilesize = 256, promote_id = NULL, ... )add_pmtiles_source( map, id, url, source_type = "vector", maxzoom = 22, tilesize = 256, promote_id = NULL, ... )
map |
A map object created by the |
id |
A unique ID for the source. |
url |
A URL pointing to the PMTiles archive. |
source_type |
The source type for MapLibre maps. Either "vector" (default) or "raster". |
maxzoom |
Only used when source_type is "raster". The maximum zoom level for the PMTiles source. Defaults to 22. |
tilesize |
Only used when source_type is "raster". The size of the tiles in the PMTiles source. Defaults to 256. |
promote_id |
An optional property name to use as the feature ID. This is required for hover effects on vector sources. |
... |
Additional arguments to be passed to the JavaScript addSource method. |
The modified map object with the new source added.
## Not run: # Visualize the Overture Maps places data as PMTiles # Works with either `maplibre()` or `mapboxgl()` library(mapgl) maplibre(style = maptiler_style("basic", variant = "dark")) |> set_projection("globe") |> add_pmtiles_source( id = "places-source", url = "https://overturemaps-tiles-us-west-2-beta.s3.amazonaws.com/2025-06-25/places.pmtiles" ) |> add_circle_layer( id = "places-layer", source = "places-source", source_layer = "place", circle_color = "cyan", circle_opacity = 0.7, circle_radius = 4, tooltip = concat( "Name: ", get_column("@name"), "<br>Confidence: ", number_format(get_column("confidence"), maximum_fraction_digits = 2) ) ) ## End(Not run)## Not run: # Visualize the Overture Maps places data as PMTiles # Works with either `maplibre()` or `mapboxgl()` library(mapgl) maplibre(style = maptiler_style("basic", variant = "dark")) |> set_projection("globe") |> add_pmtiles_source( id = "places-source", url = "https://overturemaps-tiles-us-west-2-beta.s3.amazonaws.com/2025-06-25/places.pmtiles" ) |> add_circle_layer( id = "places-layer", source = "places-source", source_layer = "place", circle_color = "cyan", circle_opacity = 0.7, circle_radius = 4, tooltip = concat( "Name: ", get_column("@name"), "<br>Confidence: ", number_format(get_column("confidence"), maximum_fraction_digits = 2) ) ) ## End(Not run)
Add a raster DEM source to a Mapbox GL or Maplibre GL map
add_raster_dem_source(map, id, url, tileSize = 512, maxzoom = NULL, ...)add_raster_dem_source(map, id, url, tileSize = 512, maxzoom = NULL, ...)
map |
A map object created by the |
id |
A unique ID for the source. |
url |
A URL pointing to the raster DEM source. |
tileSize |
The size of the raster tiles. |
maxzoom |
The maximum zoom level for the raster tiles. |
... |
Additional arguments to be passed to the JavaScript addSource method. |
The modified map object with the new source added.
Add a raster layer to a Mapbox GL map
add_raster_layer( map, id, source, source_layer = NULL, raster_brightness_max = NULL, raster_brightness_min = NULL, raster_color = NULL, raster_color_mix = NULL, raster_color_range = NULL, raster_contrast = NULL, raster_emissive_strength = NULL, raster_fade_duration = NULL, raster_hue_rotate = NULL, raster_opacity = NULL, raster_resampling = NULL, raster_saturation = NULL, visibility = "visible", slot = NULL, min_zoom = NULL, max_zoom = NULL, before_id = NULL )add_raster_layer( map, id, source, source_layer = NULL, raster_brightness_max = NULL, raster_brightness_min = NULL, raster_color = NULL, raster_color_mix = NULL, raster_color_range = NULL, raster_contrast = NULL, raster_emissive_strength = NULL, raster_fade_duration = NULL, raster_hue_rotate = NULL, raster_opacity = NULL, raster_resampling = NULL, raster_saturation = NULL, visibility = "visible", slot = NULL, min_zoom = NULL, max_zoom = NULL, before_id = NULL )
map |
A map object created by the |
id |
A unique ID for the layer. |
source |
The ID of the source. |
source_layer |
The source layer (for vector sources). |
raster_brightness_max |
The maximum brightness of the image. |
raster_brightness_min |
The minimum brightness of the image. |
raster_color |
Defines a color map for colorizing single-band raster data, parameterized by
|
raster_color_mix |
Specifies the combination of source RGB channels used to compute the raster
value when |
raster_color_range |
Specifies the value range over which |
raster_contrast |
Increase or reduce the brightness of the image. |
raster_emissive_strength |
Controls the intensity of light emitted on the source features. Requires 3D lights. |
raster_fade_duration |
The duration of the fade-in/fade-out effect. |
raster_hue_rotate |
Rotates hues around the color wheel. |
raster_opacity |
The opacity at which the raster will be drawn. |
raster_resampling |
The resampling/interpolation method to use for overscaling. Options are |
raster_saturation |
Increase or reduce the saturation of the image. |
visibility |
Whether this layer is displayed. |
slot |
An optional slot for layer order. |
min_zoom |
The minimum zoom level for the layer. |
max_zoom |
The maximum zoom level for the layer. |
before_id |
The name of the layer that this layer appears "before", allowing you to insert layers below other layers in your basemap (e.g. labels). |
The modified map object with the new raster layer added.
## Not run: mapboxgl( style = mapbox_style("dark"), zoom = 5, center = c(-75.789, 41.874) ) |> add_image_source( id = "radar", url = "https://docs.mapbox.com/mapbox-gl-js/assets/radar.gif", coordinates = list( c(-80.425, 46.437), c(-71.516, 46.437), c(-71.516, 37.936), c(-80.425, 37.936) ) ) |> add_raster_layer( id = "radar-layer", source = "radar", raster_fade_duration = 0 ) ## End(Not run)## Not run: mapboxgl( style = mapbox_style("dark"), zoom = 5, center = c(-75.789, 41.874) ) |> add_image_source( id = "radar", url = "https://docs.mapbox.com/mapbox-gl-js/assets/radar.gif", coordinates = list( c(-80.425, 46.437), c(-71.516, 46.437), c(-71.516, 37.936), c(-80.425, 37.936) ) ) |> add_raster_layer( id = "radar-layer", source = "radar", raster_fade_duration = 0 ) ## End(Not run)
Add a raster tile source to a Mapbox GL or Maplibre GL map
add_raster_source( map, id, url = NULL, tiles = NULL, tileSize = 256, maxzoom = 22, ... )add_raster_source( map, id, url = NULL, tiles = NULL, tileSize = 256, maxzoom = 22, ... )
map |
A map object created by the |
id |
A unique ID for the source. |
url |
A URL pointing to the raster tile source. (optional) |
tiles |
A vector of tile URLs for the raster source. (optional) |
tileSize |
The size of the raster tiles. |
maxzoom |
The maximum zoom level for the raster tiles. |
... |
Additional arguments to be passed to the JavaScript addSource method. |
The modified map object with the new source added.
This function adds a reset control to a Mapbox GL or MapLibre GL map. The reset control allows users to return to the original zoom level and center.
add_reset_control(map, position = "top-right", animate = TRUE, duration = NULL)add_reset_control(map, position = "top-right", animate = TRUE, duration = NULL)
map |
A map object created by the |
position |
The position of the control. Can be one of "top-left", "top-right", "bottom-left", or "bottom-right". Default is "top-right". |
animate |
Whether or not to animate the transition to the original map view; defaults to |
duration |
The length of the transition from the current view to the original view, specified in milliseconds. This argument only works with |
The modified map object with the reset control added.
## Not run: library(mapgl) mapboxgl() |> add_reset_control(position = "top-left") ## End(Not run)## Not run: library(mapgl) mapboxgl() |> add_reset_control(position = "top-left") ## End(Not run)
This function adds a scale control to a Mapbox GL or Maplibre GL map.
add_scale_control( map, position = "bottom-left", unit = "metric", max_width = 100 )add_scale_control( map, position = "bottom-left", unit = "metric", max_width = 100 )
map |
A map object created by the |
position |
The position of the control. Can be one of "top-left", "top-right", "bottom-left", or "bottom-right". Default is "bottom-left". |
unit |
The unit of the scale. Can be either "imperial", "metric", or "nautical". Default is "metric". |
max_width |
The maximum length of the scale control in pixels. Default is 100. |
The modified map object with the scale control added.
## Not run: library(mapgl) mapboxgl() |> add_scale_control(position = "bottom-right", unit = "imperial") ## End(Not run)## Not run: library(mapgl) mapboxgl() |> add_scale_control(position = "bottom-right", unit = "imperial") ## End(Not run)
This function adds a screenshot control to a Mapbox GL or MapLibre GL map. The screenshot control allows users to capture the map along with legends and attribution as a PNG image download.
add_screenshot_control( map, position = "top-right", filename = "map-screenshot", include_legend = TRUE, hide_controls = TRUE, include_scale_bar = TRUE, basemap_color = NULL, image_scale = 1, button_title = "Capture screenshot" )add_screenshot_control( map, position = "top-right", filename = "map-screenshot", include_legend = TRUE, hide_controls = TRUE, include_scale_bar = TRUE, basemap_color = NULL, image_scale = 1, button_title = "Capture screenshot" )
map |
A map object created by the |
position |
The position of the control. Can be one of "top-left", "top-right", "bottom-left", or "bottom-right". Default is "top-right". |
filename |
The base filename for the downloaded image (without extension). Default is "map-screenshot". |
include_legend |
Logical, whether to include legends in the screenshot. Default is TRUE. |
hide_controls |
Logical, whether to hide interactive controls (navigation, fullscreen, etc.) during screenshot capture. Default is TRUE. |
include_scale_bar |
Logical, whether to keep the scale bar visible in
the screenshot when |
basemap_color |
Character string or |
image_scale |
Numeric, the scale factor for the output image resolution. Default is 1. Higher values (2 or 3) produce sharper text and legend elements but increase file size. Scale 2 produces 4x larger files, scale 3 produces 9x larger files. |
button_title |
The tooltip title for the button. Default is "Capture screenshot". |
The screenshot is captured using html2canvas, which renders the map container including legends and attribution. Attribution is always included in screenshots to comply with map provider terms of service.
Most interactive controls (navigation, fullscreen, etc.) do not render correctly
in screenshots due to SVG rendering limitations and will appear as blank boxes.
The scale bar is an exception and renders correctly, which is why it is
preserved by default via include_scale_bar = TRUE.
The modified map object with the screenshot control added.
## Not run: library(mapgl) # Basic usage maplibre(style = carto_style("positron")) |> add_screenshot_control() # With scale control (recommended for screenshots) maplibre() |> add_scale_control(position = "bottom-left") |> add_screenshot_control() # With custom filename maplibre() |> add_fill_layer( id = "counties", source = list(type = "geojson", data = counties_sf) ) |> add_legend("Median Income", values = c("Low", "High")) |> add_screenshot_control( filename = "county-map", position = "top-left" ) # Exclude legend from screenshot maplibre() |> add_screenshot_control(include_legend = FALSE) ## End(Not run)## Not run: library(mapgl) # Basic usage maplibre(style = carto_style("positron")) |> add_screenshot_control() # With scale control (recommended for screenshots) maplibre() |> add_scale_control(position = "bottom-left") |> add_screenshot_control() # With custom filename maplibre() |> add_fill_layer( id = "counties", source = list(type = "geojson", data = counties_sf) ) |> add_legend("Median Income", values = c("Low", "High")) |> add_screenshot_control( filename = "county-map", position = "top-left" ) # Exclude legend from screenshot maplibre() |> add_screenshot_control(include_legend = FALSE) ## End(Not run)
Add a GeoJSON or sf source to a Mapbox GL or Maplibre GL map
add_source(map, id, data, ...)add_source(map, id, data, ...)
map |
A map object created by the |
id |
A unique ID for the source. |
data |
An sf object or a URL pointing to a remote GeoJSON file. |
... |
Additional arguments to be passed to the JavaScript addSource method. |
The modified map object with the new source added.
Add a symbol layer to a map
add_symbol_layer( map, id, source, source_layer = NULL, icon_allow_overlap = NULL, icon_anchor = NULL, icon_color = NULL, icon_color_brightness_max = NULL, icon_color_brightness_min = NULL, icon_color_contrast = NULL, icon_color_saturation = NULL, icon_emissive_strength = NULL, icon_halo_blur = NULL, icon_halo_color = NULL, icon_halo_width = NULL, icon_ignore_placement = NULL, icon_image = NULL, icon_image_cross_fade = NULL, icon_keep_upright = NULL, icon_occlusion_opacity = NULL, icon_offset = NULL, icon_opacity = NULL, icon_optional = NULL, icon_padding = NULL, icon_pitch_alignment = NULL, icon_rotate = NULL, icon_rotation_alignment = NULL, icon_size = NULL, icon_text_fit = NULL, icon_text_fit_padding = NULL, icon_translate = NULL, icon_translate_anchor = NULL, symbol_avoid_edges = NULL, symbol_placement = NULL, symbol_sort_key = NULL, symbol_spacing = NULL, symbol_z_elevate = NULL, symbol_z_offset = NULL, symbol_z_order = NULL, text_allow_overlap = NULL, text_anchor = NULL, text_color = "black", text_emissive_strength = NULL, text_field = NULL, text_font = NULL, text_halo_blur = NULL, text_halo_color = NULL, text_halo_width = NULL, text_ignore_placement = NULL, text_justify = NULL, text_keep_upright = NULL, text_letter_spacing = NULL, text_line_height = NULL, text_max_angle = NULL, text_max_width = NULL, text_occlusion_opacity = NULL, text_offset = NULL, text_opacity = NULL, text_optional = NULL, text_padding = NULL, text_pitch_alignment = NULL, text_radial_offset = NULL, text_rotate = NULL, text_rotation_alignment = NULL, text_size = NULL, text_transform = NULL, text_translate = NULL, text_translate_anchor = NULL, text_variable_anchor = NULL, text_writing_mode = NULL, visibility = "visible", slot = NULL, min_zoom = NULL, max_zoom = NULL, popup = NULL, tooltip = NULL, hover_options = NULL, before_id = NULL, filter = NULL, cluster_options = NULL )add_symbol_layer( map, id, source, source_layer = NULL, icon_allow_overlap = NULL, icon_anchor = NULL, icon_color = NULL, icon_color_brightness_max = NULL, icon_color_brightness_min = NULL, icon_color_contrast = NULL, icon_color_saturation = NULL, icon_emissive_strength = NULL, icon_halo_blur = NULL, icon_halo_color = NULL, icon_halo_width = NULL, icon_ignore_placement = NULL, icon_image = NULL, icon_image_cross_fade = NULL, icon_keep_upright = NULL, icon_occlusion_opacity = NULL, icon_offset = NULL, icon_opacity = NULL, icon_optional = NULL, icon_padding = NULL, icon_pitch_alignment = NULL, icon_rotate = NULL, icon_rotation_alignment = NULL, icon_size = NULL, icon_text_fit = NULL, icon_text_fit_padding = NULL, icon_translate = NULL, icon_translate_anchor = NULL, symbol_avoid_edges = NULL, symbol_placement = NULL, symbol_sort_key = NULL, symbol_spacing = NULL, symbol_z_elevate = NULL, symbol_z_offset = NULL, symbol_z_order = NULL, text_allow_overlap = NULL, text_anchor = NULL, text_color = "black", text_emissive_strength = NULL, text_field = NULL, text_font = NULL, text_halo_blur = NULL, text_halo_color = NULL, text_halo_width = NULL, text_ignore_placement = NULL, text_justify = NULL, text_keep_upright = NULL, text_letter_spacing = NULL, text_line_height = NULL, text_max_angle = NULL, text_max_width = NULL, text_occlusion_opacity = NULL, text_offset = NULL, text_opacity = NULL, text_optional = NULL, text_padding = NULL, text_pitch_alignment = NULL, text_radial_offset = NULL, text_rotate = NULL, text_rotation_alignment = NULL, text_size = NULL, text_transform = NULL, text_translate = NULL, text_translate_anchor = NULL, text_variable_anchor = NULL, text_writing_mode = NULL, visibility = "visible", slot = NULL, min_zoom = NULL, max_zoom = NULL, popup = NULL, tooltip = NULL, hover_options = NULL, before_id = NULL, filter = NULL, cluster_options = NULL )
map |
A map object created by the |
id |
A unique ID for the layer. |
source |
The ID of the source, alternatively an sf object (which will be converted to a GeoJSON source) or a named list that specifies |
source_layer |
The source layer (for vector sources). |
icon_allow_overlap |
If TRUE, the icon will be visible even if it collides with other previously drawn symbols. |
icon_anchor |
Part of the icon placed closest to the anchor. |
icon_color |
The color of the icon. This is not supported for many Mapbox icons; read more at https://docs.mapbox.com/help/troubleshooting/using-recolorable-images-in-mapbox-maps/. |
icon_color_brightness_max |
The maximum brightness of the icon color. |
icon_color_brightness_min |
The minimum brightness of the icon color. |
icon_color_contrast |
The contrast of the icon color. |
icon_color_saturation |
The saturation of the icon color. |
icon_emissive_strength |
The strength of the icon's emissive color. |
icon_halo_blur |
The blur applied to the icon's halo. |
icon_halo_color |
The color of the icon's halo. |
icon_halo_width |
The width of the icon's halo. |
icon_ignore_placement |
If TRUE, the icon will be visible even if it collides with other symbols. |
icon_image |
Name of image in sprite to use for drawing an image background.
To use values in a column of your input dataset, use |
icon_image_cross_fade |
The cross-fade parameter for the icon image. |
icon_keep_upright |
If TRUE, the icon will be kept upright. |
icon_occlusion_opacity |
The opacity at which the icon will be drawn when occluded by 3D objects. Value between 0 and 1; 0 hides occluded icons. |
icon_offset |
Offset distance of icon. |
icon_opacity |
The opacity at which the icon will be drawn. |
icon_optional |
If TRUE, the icon will be optional. |
icon_padding |
Padding around the icon. |
icon_pitch_alignment |
Alignment of the icon with respect to the pitch of the map. |
icon_rotate |
Rotates the icon clockwise. |
icon_rotation_alignment |
Alignment of the icon with respect to the map. |
icon_size |
The size of the icon, specified relative to the original size of the image. For example, a value of 5 would make the icon 5 times larger than the original size, whereas a value of 0.5 would make the icon half the size of the original. |
icon_text_fit |
Scales the text to fit the icon. |
icon_text_fit_padding |
Padding for text fitting the icon. |
icon_translate |
The offset distance of the icon. |
icon_translate_anchor |
Controls the frame of reference for |
symbol_avoid_edges |
If TRUE, the symbol will be avoided when near the edges. |
symbol_placement |
Placement of the symbol on the map. |
symbol_sort_key |
Sorts features in ascending order based on this value. |
symbol_spacing |
Spacing between symbols. |
symbol_z_elevate |
If |
symbol_z_offset |
The elevation of the symbol, in meters. Use |
symbol_z_order |
Orders the symbol z-axis. |
text_allow_overlap |
If TRUE, the text will be visible even if it collides with other previously drawn symbols. |
text_anchor |
Part of the text placed closest to the anchor. |
text_color |
The color of the text. |
text_emissive_strength |
The strength of the text's emissive color. |
text_field |
Value to use for a text label. |
text_font |
Font stack to use for displaying text. |
text_halo_blur |
The blur applied to the text's halo. |
text_halo_color |
The color of the text's halo. |
text_halo_width |
The width of the text's halo. |
text_ignore_placement |
If TRUE, the text will be visible even if it collides with other symbols. |
text_justify |
The justification of the text. |
text_keep_upright |
If TRUE, the text will be kept upright. |
text_letter_spacing |
Spacing between text letters. |
text_line_height |
Height of the text lines. |
text_max_angle |
Maximum angle of the text. |
text_max_width |
Maximum width of the text. |
text_occlusion_opacity |
The opacity at which the text will be drawn when occluded by 3D objects. Value between 0 and 1; 0 hides occluded text. |
text_offset |
Offset distance of text. |
text_opacity |
The opacity at which the text will be drawn. |
text_optional |
If TRUE, the text will be optional. |
text_padding |
Padding around the text. |
text_pitch_alignment |
Alignment of the text with respect to the pitch of the map. |
text_radial_offset |
Radial offset of the text. |
text_rotate |
Rotates the text clockwise. |
text_rotation_alignment |
Alignment of the text with respect to the map. |
text_size |
The size of the text. |
text_transform |
Transform applied to the text. |
text_translate |
The offset distance of the text. |
text_translate_anchor |
Controls the frame of reference for |
text_variable_anchor |
Variable anchor for the text. |
text_writing_mode |
Writing mode for the text. |
visibility |
Whether this layer is displayed. |
slot |
An optional slot for layer order. |
min_zoom |
The minimum zoom level for the layer. |
max_zoom |
The maximum zoom level for the layer. |
popup |
A column name containing information to display in a popup on click. Columns containing HTML will be parsed. |
tooltip |
A column name containing information to display in a tooltip on hover. Columns containing HTML will be parsed. |
hover_options |
A named list of options for highlighting features in the layer on hover. Not all elements of SVG icons can be styled. |
before_id |
The name of the layer that this layer appears "before", allowing you to insert layers below other layers in your basemap (e.g. labels). |
filter |
An optional filter expression to subset features in the layer. |
cluster_options |
A list of options for clustering symbols, created by the Updating a clustered layer in Shiny: the shortcut creates three layers ( |
The modified map object with the new symbol layer added.
## Not run: library(mapgl) library(sf) library(dplyr) # Set seed for reproducibility set.seed(1234) # Define the bounding box for Washington DC (approximately) bbox <- st_bbox( c( xmin = -77.119759, ymin = 38.791645, xmax = -76.909393, ymax = 38.995548 ), crs = st_crs(4326) ) # Generate 30 random points within the bounding box random_points <- st_as_sf( data.frame( id = 1:30, lon = runif(30, bbox["xmin"], bbox["xmax"]), lat = runif(30, bbox["ymin"], bbox["ymax"]) ), coords = c("lon", "lat"), crs = 4326 ) # Assign random icons icons <- c("music", "bar", "theatre", "bicycle") random_points <- random_points |> mutate(icon = sample(icons, n(), replace = TRUE)) # Map with icons mapboxgl(style = mapbox_style("light")) |> fit_bounds(random_points, animate = FALSE) |> add_symbol_layer( id = "points-of-interest", source = random_points, icon_image = c("get", "icon"), icon_allow_overlap = TRUE, tooltip = "icon" ) ## End(Not run)## Not run: library(mapgl) library(sf) library(dplyr) # Set seed for reproducibility set.seed(1234) # Define the bounding box for Washington DC (approximately) bbox <- st_bbox( c( xmin = -77.119759, ymin = 38.791645, xmax = -76.909393, ymax = 38.995548 ), crs = st_crs(4326) ) # Generate 30 random points within the bounding box random_points <- st_as_sf( data.frame( id = 1:30, lon = runif(30, bbox["xmin"], bbox["xmax"]), lat = runif(30, bbox["ymin"], bbox["ymax"]) ), coords = c("lon", "lat"), crs = 4326 ) # Assign random icons icons <- c("music", "bar", "theatre", "bicycle") random_points <- random_points |> mutate(icon = sample(icons, n(), replace = TRUE)) # Map with icons mapboxgl(style = mapbox_style("light")) |> fit_bounds(random_points, animate = FALSE) |> add_symbol_layer( id = "points-of-interest", source = random_points, icon_image = c("get", "icon"), icon_allow_overlap = TRUE, tooltip = "icon" ) ## End(Not run)
Adds an interactive time scrubber with a histogram to the map. The control filters temporal data by dragging a range across a bar chart. It can drive one or several layers at once — both flowmap layers and ordinary Mapbox/MapLibre layers (circle, fill, line, symbol, etc.) whose source features carry a time property.
add_time_control( map, data, time_column, layer_id = NULL, feature_time_property = NULL, feature_time_format = c("iso", "epoch_ms", "epoch_s"), time_interval = c("hour", "day"), position = "bottom-left", initial_range = NULL, loop = TRUE, speed = 500, autoplay = FALSE, accent_color = "#00bcd4", dark_mode = TRUE, draggable = TRUE, collapsible = FALSE, collapsed = FALSE, title = NULL )add_time_control( map, data, time_column, layer_id = NULL, feature_time_property = NULL, feature_time_format = c("iso", "epoch_ms", "epoch_s"), time_interval = c("hour", "day"), position = "bottom-left", initial_range = NULL, loop = TRUE, speed = 500, autoplay = FALSE, accent_color = "#00bcd4", dark_mode = TRUE, draggable = TRUE, collapsible = FALSE, collapsed = FALSE, title = NULL )
map |
A map object created by |
data |
A data frame containing the temporal data used to build the histogram (bin counts and extent). |
time_column |
The name of the column in |
layer_id |
Target layer ID(s) to filter. Either a character vector of
layer IDs (flowmap and/or ordinary layers), or |
feature_time_property |
For ordinary (non-flowmap) target layers, the
name of the feature property holding the timestamp. Defaults to
|
feature_time_format |
How the timestamp is stored on ordinary target
layers' source features: |
time_interval |
The aggregation interval for the histogram: |
position |
The position of the control: |
initial_range |
Optional vector of two dates/timestamps for the initial time filter range. |
loop |
Logical; whether to loop the playback. |
speed |
Playback speed in milliseconds per step (default 500). |
autoplay |
Logical; if |
accent_color |
Color for the bars and selection handles. |
dark_mode |
Logical; whether to use a dark theme for the widget. |
draggable |
Logical; if |
collapsible |
Logical; if |
collapsed |
Logical; whether to start in the collapsed state. Implies
|
title |
Optional short title shown in the header (useful when the control is draggable or collapsible). |
For ordinary layers, the control sets a Mapbox filter expression of the
form [">=", ["get", feature_time_property], start] && ["<", ..., end].
The property is assumed to be an ISO 8601 timestamp string by default; pass
feature_time_format = "epoch_ms" (or "epoch_s") if your source data
encodes time as numeric epoch milliseconds (or seconds).
For flowmap layers the control updates the selectedTimeRange of the
flowmap filter via the flowmap.gl plugin.
Hold Shift while dragging on the histogram to add another selected time range. Multiple ranges are combined with OR semantics when filtering target layers.
The modified map object.
# Create a flowmap centered on Montréal using the bundled datasets maplibre( style = carto_style("dark-matter"), center = c(-73.58, 45.50), zoom = 11, projection = "mercator" ) |> add_flowmap( id = "bixi-rides", locations = bixi_locations, flows = bixi_flows, flow_time_column = "time", flow_color_scheme = "Teal", flow_dark_mode = TRUE ) |> add_time_control( data = bixi_flows, time_column = "time", time_interval = "hour", title = "BIXI Montréal Rides" )# Create a flowmap centered on Montréal using the bundled datasets maplibre( style = carto_style("dark-matter"), center = c(-73.58, 45.50), zoom = 11, projection = "mercator" ) |> add_flowmap( id = "bixi-rides", locations = bixi_locations, flows = bixi_flows, flow_time_column = "time", flow_color_scheme = "Teal", flow_dark_mode = TRUE ) |> add_time_control( data = bixi_flows, time_column = "time", time_interval = "hour", title = "BIXI Montréal Rides" )
Add a vector tile source to a Mapbox GL or Maplibre GL map
add_vector_source(map, id, url = NULL, tiles = NULL, promote_id = NULL, ...)add_vector_source(map, id, url = NULL, tiles = NULL, promote_id = NULL, ...)
map |
A map object created by the |
id |
A unique ID for the source. |
url |
A URL pointing to the vector tile source. |
tiles |
A vector of tile URLs, typically in the format "https://example.com/{z}/{x}/{y}.mvt" or similar. |
promote_id |
An optional property name to use as the feature ID. This is required for hover effects on vector tiles. |
... |
Additional arguments to be passed to the JavaScript addSource method. |
The modified map object with the new source added.
Add a video source to a Mapbox GL or Maplibre GL map
add_video_source(map, id, urls, coordinates)add_video_source(map, id, urls, coordinates)
map |
A map object created by the |
id |
A unique ID for the source. |
urls |
A vector of URLs pointing to the video sources. |
coordinates |
A list of coordinates specifying the video corners in clockwise order: top left, top right, bottom right, bottom left. |
The modified map object with the new source added.
This function allows you to add additional data layers to existing maps created with mapboxgl_view() or maplibre_view(), enabling composition of multiple datasets on a single map.
add_view( map, data, color = "gold", column = NULL, n = NULL, palette = viridisLite::viridis, layer_id = NULL, legend = FALSE, legend_position = "bottom-left" )add_view( map, data, color = "gold", column = NULL, n = NULL, palette = viridisLite::viridis, layer_id = NULL, legend = FALSE, legend_position = "bottom-left" )
map |
A map object created by mapboxgl_view(), maplibre_view(), mapboxgl(), or maplibre() |
data |
An sf object, SpatRaster, or RasterLayer to visualize |
color |
The color used to visualize points, lines, or polygons if |
column |
The name of the column to visualize. If NULL (default), geometries are shown with default styling. |
n |
Number of quantile breaks for numeric columns. If specified, uses step_expr() instead of interpolate(). |
palette |
Color palette function that takes n and returns a character vector of colors. Defaults to viridisLite::viridis. |
layer_id |
The layer ID to use for the visualization. If NULL, a unique ID will be auto-generated. |
legend |
Logical, whether to add a legend when a column is specified. Defaults to FALSE for subsequent layers to avoid overwriting existing legends. |
legend_position |
The position of the legend on the map. Defaults to "bottom-left". |
The map object with the new layer added
## Not run: library(sf) nc <- st_read(system.file("shape/nc.shp", package = "sf")) # Basic layering mapboxgl_view(nc) |> add_view(nc[1:10, ], color = "red", layer_id = "subset") # Layer different geometries mapboxgl_view(polygons) |> add_view(points, color = "blue") |> add_view(lines, color = "green") # Add raster data mapboxgl_view(boundaries) |> add_view(elevation_raster, layer_id = "elevation") ## End(Not run)## Not run: library(sf) nc <- st_read(system.file("shape/nc.shp", package = "sf")) # Basic layering mapboxgl_view(nc) |> add_view(nc[1:10, ], color = "red", layer_id = "subset") # Layer different geometries mapboxgl_view(polygons) |> add_view(points, color = "blue") |> add_view(lines, color = "green") # Add raster data mapboxgl_view(boundaries) |> add_view(elevation_raster, layer_id = "elevation") ## End(Not run)
Creates a minimal map style with only a solid background color (or pattern) and no basemap tiles. Useful when you want to display data layers without any underlying map features.
basemap_style(color = "white", pattern = NULL)basemap_style(color = "white", pattern = NULL)
color |
Character string. The background color. Default |
pattern |
Character string or |
A list representing a minimal map style, suitable for passing to
the style parameter of maplibre() or mapboxgl().
## Not run: library(mapgl) # Solid color background maplibre(style = basemap_style("lightgrey")) |> add_fill_layer( id = "data", source = my_sf_data, fill_color = "steelblue" ) # Background pattern (image must be loaded with add_image()) maplibre(style = basemap_style(pattern = "parchment")) |> add_image("parchment", "parchment.jpg") |> add_line_layer( id = "borders", source = my_sf_data, line_color = "#2c1810" ) ## End(Not run)## Not run: library(mapgl) # Solid color background maplibre(style = basemap_style("lightgrey")) |> add_fill_layer( id = "data", source = my_sf_data, fill_color = "steelblue" ) # Background pattern (image must be loaded with add_image()) maplibre(style = basemap_style(pattern = "parchment")) |> add_image("parchment", "parchment.jpg") |> add_line_layer( id = "borders", source = my_sf_data, line_color = "#2c1810" ) ## End(Not run)
Bivariate color palettes
bivariate_palettes(palette = NULL)bivariate_palettes(palette = NULL)
palette |
Optional palette name. If NULL, returns all palettes. |
A named list of 3 by 3 color matrices, or one matrix if palette is provided.
Create a bivariate color scale
bivariate_scale( data = NULL, x, y, x_values = NULL, y_values = NULL, x_breaks = NULL, y_breaks = NULL, method = "quantile", colors = NULL, palette = "blue_pink", na_color = "lightgrey" )bivariate_scale( data = NULL, x, y, x_values = NULL, y_values = NULL, x_breaks = NULL, y_breaks = NULL, method = "quantile", colors = NULL, palette = "blue_pink", na_color = "lightgrey" )
data |
A data frame or sf object containing the variables. |
x |
The name of the first numeric column. |
y |
The name of the second numeric column. |
x_values |
Optional numeric vector for the first variable. |
y_values |
Optional numeric vector for the second variable. |
x_breaks |
Optional numeric vector of four increasing break values for
the x variable. If NULL, breaks are computed from |
y_breaks |
Optional numeric vector of four increasing break values for
the y variable. If NULL, breaks are computed from |
method |
Classification method. The MVP supports |
colors |
A 3 by 3 matrix or 9-color vector. If NULL, a built-in palette is used. |
palette |
Built-in palette name. Defaults to |
na_color |
Color for missing values. Defaults to |
A mapgl_bivariate_scale object.
A dataset containing hourly aggregated bike sharing trips between BIXI stations in Montréal during the week of July 1 to July 7, 2019.
bixi_flowsbixi_flows
A data frame with 6,092 rows and 4 variables:
Hourly timestamp (POSIXct, UTC)
Origin station ID (factor, matching bixi_locations$id)
Destination station ID (factor, matching bixi_locations$id)
Aggregated number of bike sharing trips in that hour (integer)
To minimize the package footprint, the dataset has been truncated to a
minimum of three trips (retaining only flows where count > 2),
which reduces the rows from 213,227 to 6,092, and compresses the final size
to just ~22 KB.
BIXI Montréal Open Data (https://bixi.com/fr/donnees-ouvertes). Prepared for https://github.com/FlowmapBlue/FlowmapBlue by Ilya Boyandin (https://twitter.com/ilyabo). Original interactive visualization on Flowmap.blue: https://www.flowmap.blue/1qTVOzkPB7U1ySI4g4uPtVBzzEDCI8n1WXAmQeZL15fE
# Check first few records print(head(bixi_flows))# Check first few records print(head(bixi_flows))
A dataset containing the names and coordinates of BIXI bicycle sharing stations in Montréal, Quebec, Canada.
bixi_locationsbixi_locations
A data frame with 618 rows and 4 variables:
Unique station ID (character, e.g., "4000", "MTL-ECO5.1-01")
Station name (character, e.g., "Jeanne-d'Arc / Ontario")
Latitude coordinate (numeric)
Longitude coordinate (numeric)
BIXI Montréal Open Data (https://bixi.com/fr/donnees-ouvertes). Prepared for https://github.com/FlowmapBlue/FlowmapBlue by Ilya Boyandin (https://twitter.com/ilyabo).
# Convert to sf object to view on a map if (requireNamespace("sf", quietly = TRUE)) { bixi_sf <- sf::st_as_sf(bixi_locations, coords = c("lon", "lat"), crs = 4326) print(head(bixi_sf)) }# Convert to sf object to view on a map if (requireNamespace("sf", quietly = TRUE)) { bixi_sf <- sf::st_as_sf(bixi_locations, coords = c("lon", "lat"), crs = 4326) print(head(bixi_sf)) }
Get CARTO Style URL
carto_style(style_name)carto_style(style_name)
style_name |
The name of the style (e.g., "voyager", "positron", "dark-matter"). |
The style URL corresponding to the given style name.
These functions extract different components from mapgl_classification objects
(created by step_equal_interval(), step_quantile(), step_jenks()) and
mapgl_continuous_scale objects (created by interpolate_palette()).
get_legend_labels( scale, format = "none", currency_symbol = "$", digits = 2, big_mark = ",", suffix = "", prefix = "" ) get_legend_colors(scale) get_breaks(scale) ## S3 method for class 'mapgl_classification' print(x, format = "none", ...) ## S3 method for class 'mapgl_continuous_scale' print(x, format = "none", ...)get_legend_labels( scale, format = "none", currency_symbol = "$", digits = 2, big_mark = ",", suffix = "", prefix = "" ) get_legend_colors(scale) get_breaks(scale) ## S3 method for class 'mapgl_classification' print(x, format = "none", ...) ## S3 method for class 'mapgl_continuous_scale' print(x, format = "none", ...)
scale |
A mapgl_classification or mapgl_continuous_scale object. |
format |
A character string specifying the format type for labels. Options include:
|
currency_symbol |
The currency symbol to use when format = "currency". Defaults to "$". |
digits |
The number of decimal places to display. Defaults to 2. |
big_mark |
The character to use as thousands separator. Defaults to ",". |
suffix |
An optional suffix to add to all values (e.g., "km", "mph"). |
prefix |
An optional prefix to add to all values (useful for compact currency like "$1.2K"). |
x |
A mapgl_classification or mapgl_continuous_scale object to print. |
... |
Additional arguments passed to formatting functions. |
A character vector of formatted legend labels
A character vector of colors
A numeric vector of break values
## Not run: # Texas county income data library(tidycensus) tx <- get_acs(geography = "county", variables = "B19013_001", state = "TX", geometry = TRUE) # Classification examples eq_class <- step_equal_interval("estimate", tx$estimate, n = 4) labels <- get_legend_labels(eq_class, format = "currency") colors <- get_legend_colors(eq_class) breaks <- get_breaks(eq_class) # Continuous scale examples scale <- interpolate_palette("estimate", tx$estimate, method = "quantile", n = 5) labels <- get_legend_labels(scale, format = "compact", prefix = "$") colors <- get_legend_colors(scale) ## End(Not run)## Not run: # Texas county income data library(tidycensus) tx <- get_acs(geography = "county", variables = "B19013_001", state = "TX", geometry = TRUE) # Classification examples eq_class <- step_equal_interval("estimate", tx$estimate, n = 4) labels <- get_legend_labels(eq_class, format = "currency") colors <- get_legend_colors(eq_class) breaks <- get_breaks(eq_class) # Continuous scale examples scale <- interpolate_palette("estimate", tx$estimate, method = "quantile", n = 5) labels <- get_legend_labels(scale, format = "compact", prefix = "$") colors <- get_legend_colors(scale) ## End(Not run)
This function allows you to remove specific controls or all controls from a map.
You can target controls by their type names, which correspond to the function
names used to add them (e.g., "navigation" for controls added with add_navigation_control).
clear_controls(map, controls = NULL)clear_controls(map, controls = NULL)
map |
A map object created by the |
controls |
A character vector of control types to remove, or NULL to remove all controls. Control types include: "navigation", "draw", "fullscreen", "scale", "geolocate", "geocoder", "layers", "reset", "globe_minimap", or custom control IDs. If NULL (default), all controls will be removed. |
The modified map object with specified controls removed.
## Not run: library(shiny) library(mapgl) # Clear all controls maplibre_proxy("map") |> clear_controls() # Clear specific controls maplibre_proxy("map") |> clear_controls("navigation") # Clear multiple controls maplibre_proxy("map") |> clear_controls(c("draw", "navigation")) # Clear a custom control by ID maplibre_proxy("map") |> clear_controls("my_custom_control") ## End(Not run)## Not run: library(shiny) library(mapgl) # Clear all controls maplibre_proxy("map") |> clear_controls() # Clear specific controls maplibre_proxy("map") |> clear_controls("navigation") # Clear multiple controls maplibre_proxy("map") |> clear_controls(c("draw", "navigation")) # Clear a custom control by ID maplibre_proxy("map") |> clear_controls("my_custom_control") ## End(Not run)
This function removes all features that have been drawn using the draw control on a Mapbox GL or MapLibre GL map in a Shiny application.
clear_drawn_features(map)clear_drawn_features(map)
map |
A proxy object created by the |
The modified map object with all drawn features cleared.
## Not run: # In a Shiny application library(shiny) library(mapgl) ui <- fluidPage( mapboxglOutput("map"), actionButton("clear_btn", "Clear Drawn Features") ) server <- function(input, output, session) { output$map <- renderMapboxgl({ mapboxgl( style = mapbox_style("streets"), center = c(-74.50, 40), zoom = 9 ) |> add_draw_control() }) observeEvent(input$clear_btn, { mapboxgl_proxy("map") |> clear_drawn_features() }) } shinyApp(ui, server) ## End(Not run)## Not run: # In a Shiny application library(shiny) library(mapgl) ui <- fluidPage( mapboxglOutput("map"), actionButton("clear_btn", "Clear Drawn Features") ) server <- function(input, output, session) { output$map <- renderMapboxgl({ mapboxgl( style = mapbox_style("streets"), center = c(-74.50, 40), zoom = 9 ) |> add_draw_control() }) observeEvent(input$clear_btn, { mapboxgl_proxy("map") |> clear_drawn_features() }) } shinyApp(ui, server) ## End(Not run)
This function allows one or more layers to be removed from an existing Mapbox GL map using a proxy object.
clear_layer(proxy, layer_id)clear_layer(proxy, layer_id)
proxy |
A proxy object created by |
layer_id |
A character vector of layer IDs to be removed. Can be a single layer ID or multiple layer IDs. |
The updated proxy object.
Remove one or more legends from a Mapbox GL or MapLibre GL map in a Shiny application.
clear_legend(map, legend_ids = NULL)clear_legend(map, legend_ids = NULL)
map |
A map proxy object created by |
legend_ids |
Optional. A character vector of legend IDs to clear. If not provided, all legends will be cleared. |
The updated map proxy object with the specified legend(s) cleared.
This function can only be used with map proxy objects in Shiny applications. It cannot be used with static map objects.
## Not run: # In a Shiny server function: # Clear all legends observeEvent(input$clear_all, { mapboxgl_proxy("map") %>% clear_legend() }) # Clear specific legends by ID observeEvent(input$clear_specific, { mapboxgl_proxy("map") %>% clear_legend(legend_ids = c("legend-1", "legend-2")) }) # Clear legend after removing a layer observeEvent(input$remove_layer, { mapboxgl_proxy("map") %>% remove_layer("my_layer") %>% clear_legend(legend_ids = "my_layer_legend") }) ## End(Not run)## Not run: # In a Shiny server function: # Clear all legends observeEvent(input$clear_all, { mapboxgl_proxy("map") %>% clear_legend() }) # Clear specific legends by ID observeEvent(input$clear_specific, { mapboxgl_proxy("map") %>% clear_legend(legend_ids = c("legend-1", "legend-2")) }) # Clear legend after removing a layer observeEvent(input$remove_layer, { mapboxgl_proxy("map") %>% remove_layer("my_layer") %>% clear_legend(legend_ids = "my_layer_legend") }) ## End(Not run)
Clear markers from a map in a Shiny session
clear_markers(map)clear_markers(map)
map |
A map object created by the |
The modified map object with the markers cleared.
This function creates a list of options for clustering circle layers.
cluster_options( max_zoom = 14, cluster_radius = 50, color_stops = c("#51bbd6", "#f1f075", "#f28cb1"), radius_stops = c(20, 30, 40), count_stops = c(0, 100, 750), circle_blur = NULL, circle_opacity = NULL, circle_stroke_color = NULL, circle_stroke_opacity = NULL, circle_stroke_width = NULL, text_color = "black", count_format = c("abbreviated", "grouped", "raw") )cluster_options( max_zoom = 14, cluster_radius = 50, color_stops = c("#51bbd6", "#f1f075", "#f28cb1"), radius_stops = c(20, 30, 40), count_stops = c(0, 100, 750), circle_blur = NULL, circle_opacity = NULL, circle_stroke_color = NULL, circle_stroke_opacity = NULL, circle_stroke_width = NULL, text_color = "black", count_format = c("abbreviated", "grouped", "raw") )
max_zoom |
The maximum zoom level at which to cluster points. |
cluster_radius |
The radius of each cluster when clustering points. |
color_stops |
A vector of colors for the circle color step expression. |
radius_stops |
A vector of radii for the circle radius step expression. |
count_stops |
A vector of point counts for both color and radius step expressions. |
circle_blur |
Amount to blur the circle. |
circle_opacity |
The opacity of the circle. |
circle_stroke_color |
The color of the circle's stroke. |
circle_stroke_opacity |
The opacity of the circle's stroke. |
circle_stroke_width |
The width of the circle's stroke. |
text_color |
The color to use for labels on the cluster circles. |
count_format |
The formatting of the text labels on the cluster circles to represent the counts. |
A list of cluster options.
cluster_options( max_zoom = 14, cluster_radius = 50, color_stops = c("#51bbd6", "#f1f075", "#f28cb1"), radius_stops = c(20, 30, 40), count_stops = c(0, 100, 750), circle_blur = 1, circle_opacity = 0.8, circle_stroke_color = "#ffffff", circle_stroke_width = 2 )cluster_options( max_zoom = 14, cluster_radius = 50, color_stops = c("#51bbd6", "#f1f075", "#f28cb1"), radius_stops = c(20, 30, 40), count_stops = c(0, 100, 750), circle_blur = 1, circle_opacity = 0.8, circle_stroke_color = "#ffffff", circle_stroke_width = 2 )
This function creates a comparison view between two Mapbox GL or Maplibre GL maps, allowing users to either swipe between the two maps or view them side-by-side with synchronized navigation.
compare( map1, map2, width = "100%", height = NULL, elementId = NULL, mousemove = FALSE, orientation = "vertical", mode = "swipe", swiper_color = NULL, laser = FALSE, laser_color = "#ff2d55", laser_size = 14 )compare( map1, map2, width = "100%", height = NULL, elementId = NULL, mousemove = FALSE, orientation = "vertical", mode = "swipe", swiper_color = NULL, laser = FALSE, laser_color = "#ff2d55", laser_size = 14 )
map1 |
A |
map2 |
A |
width |
Width of the map container. |
height |
Height of the map container. |
elementId |
An optional string specifying the ID of the container for the comparison. If NULL, a unique ID will be generated. |
mousemove |
A logical value indicating whether to enable swiping during cursor movement (rather than only when clicked). Only applicable when |
orientation |
A string specifying the orientation of the swiper or the side-by-side layout, either "horizontal" or "vertical". |
mode |
A string specifying the comparison mode: "swipe" (default) for a swipeable comparison with a slider, or "sync" for synchronized maps displayed next to each other. |
swiper_color |
An optional CSS color value (e.g., "#000000", "rgb(0,0,0)", "black") to customize the color of the swiper handle. Only applicable when |
laser |
Logical; if |
laser_color |
CSS color for the laser pointer. |
laser_size |
Size of the laser pointer in pixels. |
The compare() function supports two modes:
mode="swipe" (default) - Creates a swipeable interface with a slider to reveal portions of each map
mode="sync" - Places the maps next to each other with synchronized navigation
In both modes, navigation (panning, zooming, rotating, tilting) is synchronized between the maps.
The compare widget can be used in Shiny applications with the following functions:
mapboxglCompareOutput() / renderMapboxglCompare() - For Mapbox GL comparisons
maplibreCompareOutput() / renderMaplibreCompare() - For Maplibre GL comparisons
mapboxgl_compare_proxy() / maplibre_compare_proxy() - For updating maps in a compare widget
After creating a compare widget in a Shiny app, you can use the proxy functions to update either the "before"
(left/top) or "after" (right/bottom) map. The proxy objects work with all the regular map update functions like set_style(),
set_paint_property(), etc.
To get a proxy that targets a specific map in the comparison:
# Access the left/top map
left_proxy <- maplibre_compare_proxy("compare_id", map_side = "before")
# Access the right/bottom map
right_proxy <- maplibre_compare_proxy("compare_id", map_side = "after")
The compare widget also provides Shiny input values for view state and clicks. For a compare widget with ID "mycompare", you'll have:
input$mycompare_before_view - View state (center, zoom, bearing, pitch) of the left/top map
input$mycompare_after_view - View state of the right/bottom map
input$mycompare_before_click - Click events on the left/top map
input$mycompare_after_click - Click events on the right/bottom map
A comparison widget.
## Not run: library(mapgl) m1 <- mapboxgl(style = mapbox_style("light")) m2 <- mapboxgl(style = mapbox_style("dark")) # Default swipe mode compare(m1, m2) # Synchronized side-by-side mode compare(m1, m2, mode = "sync") # Synchronized maps with a laser pointer compare(m1, m2, mode = "sync", laser = TRUE) # Custom swiper color compare(m1, m2, swiper_color = "#FF0000") # Red swiper # Shiny example library(shiny) ui <- fluidPage( maplibreCompareOutput("comparison") ) server <- function(input, output, session) { output$comparison <- renderMaplibreCompare({ compare( maplibre(style = carto_style("positron")), maplibre(style = carto_style("dark-matter")), mode = "sync" ) }) # Update the right map observe({ right_proxy <- maplibre_compare_proxy("comparison", map_side = "after") set_style(right_proxy, carto_style("voyager")) }) # Example with custom swiper color output$comparison2 <- renderMaplibreCompare({ compare( maplibre(style = carto_style("positron")), maplibre(style = carto_style("dark-matter")), swiper_color = "#3498db" # Blue swiper ) }) } ## End(Not run)## Not run: library(mapgl) m1 <- mapboxgl(style = mapbox_style("light")) m2 <- mapboxgl(style = mapbox_style("dark")) # Default swipe mode compare(m1, m2) # Synchronized side-by-side mode compare(m1, m2, mode = "sync") # Synchronized maps with a laser pointer compare(m1, m2, mode = "sync", laser = TRUE) # Custom swiper color compare(m1, m2, swiper_color = "#FF0000") # Red swiper # Shiny example library(shiny) ui <- fluidPage( maplibreCompareOutput("comparison") ) server <- function(input, output, session) { output$comparison <- renderMaplibreCompare({ compare( maplibre(style = carto_style("positron")), maplibre(style = carto_style("dark-matter")), mode = "sync" ) }) # Update the right map observe({ right_proxy <- maplibre_compare_proxy("comparison", map_side = "after") set_style(right_proxy, carto_style("voyager")) }) # Example with custom swiper color output$comparison2 <- renderMaplibreCompare({ compare( maplibre(style = carto_style("positron")), maplibre(style = carto_style("dark-matter")), swiper_color = "#3498db" # Blue swiper ) }) } ## End(Not run)
This function creates a concatenation expression that combines multiple values or expressions into a single string. Useful for creating dynamic tooltips or labels.
concat(...)concat(...)
... |
Values or expressions to concatenate. Can be strings, numbers, or other expressions like |
A list representing the concatenation expression.
# Create a dynamic tooltip concat("<strong>Name:</strong> ", get_column("name"), "<br>Value: ", get_column("value"))# Create a dynamic tooltip concat("<strong>Name:</strong> ", get_column("name"), "<br>Value: ", get_column("value"))
This helper creates one field definition for the attributes argument in
add_draw_control(). The field name comes from the name used in the
attributes list.
draw_attribute( type = NULL, label = NULL, choices = NULL, default = NULL, required = FALSE, placeholder = NULL, min = NULL, max = NULL, step = NULL )draw_attribute( type = NULL, label = NULL, choices = NULL, default = NULL, required = FALSE, placeholder = NULL, min = NULL, max = NULL, step = NULL )
type |
Input type for the editor. Supported values are |
label |
Optional label shown in the editor. Defaults to the field name. |
choices |
Values for |
default |
Optional default value. Defaults are applied to newly drawn features only; existing feature properties are preserved. |
required |
Logical; whether the browser should require a value before saving. |
placeholder |
Optional placeholder for text, textarea, and number inputs. |
min, max, step
|
Optional numeric input constraints for |
A list suitable for one entry in add_draw_control(attributes = ).
draw_attribute("select", choices = c("candidate", "active", "rejected")) draw_attribute("textarea", label = "Notes") draw_attribute("numeric", min = 0, max = 1, step = 0.1, default = 1) ## Not run: mapboxgl() |> add_draw_control( attributes = list( status = draw_attribute( "select", choices = c(Candidate = "candidate", Active = "active") ), notes = draw_attribute("textarea"), value = draw_attribute("numeric") ) ) ## End(Not run)draw_attribute("select", choices = c("candidate", "active", "rejected")) draw_attribute("textarea", label = "Notes") draw_attribute("numeric", min = 0, max = 1, step = 0.1, default = 1) ## Not run: mapboxgl() |> add_draw_control( attributes = list( status = draw_attribute( "select", choices = c(Candidate = "candidate", Active = "active") ), notes = draw_attribute("textarea"), value = draw_attribute("numeric") ) ) ## End(Not run)
Ease to a given view
ease_to(map, center, zoom = NULL, ...)ease_to(map, center, zoom = NULL, ...)
map |
A map object created by the |
center |
A numeric vector of length 2 specifying the target center of the map (longitude, latitude). |
zoom |
The target zoom level. |
... |
Additional named arguments for easing to the view. |
The updated map object.
This function enables hover functionality for maplibre and mapboxgl widgets
in Shiny applications, providing _hover and _feature_hover input values.
enable_shiny_hover(map, coordinates = TRUE, features = TRUE, layer_id = NULL)enable_shiny_hover(map, coordinates = TRUE, features = TRUE, layer_id = NULL)
map |
A maplibre or mapboxgl widget object. |
coordinates |
Logical. If TRUE, provides general mouse coordinates via |
features |
Logical. If TRUE, provides feature information via |
layer_id |
Character. If provided, only features from the specified layer will be included in the |
The modified map object with hover events enabled.
## Not run: library(shiny) library(mapgl) ui <- fluidPage( maplibreOutput("map"), verbatimTextOutput("hover_info") ) server <- function(input, output) { output$map <- renderMaplibre({ maplibre() |> enable_shiny_hover() }) output$hover_info <- renderText({ paste("Mouse at:", input$map_hover$lng, input$map_hover$lat) }) } shinyApp(ui, server) ## End(Not run)## Not run: library(shiny) library(mapgl) ui <- fluidPage( maplibreOutput("map"), verbatimTextOutput("hover_info") ) server <- function(input, output) { output$map <- renderMaplibre({ maplibre() |> enable_shiny_hover() }) output$hover_info <- renderText({ paste("Mouse at:", input$map_hover$lng, input$map_hover$lat) }) } shinyApp(ui, server) ## End(Not run)
Generates a style URL for the ArcGIS Open Basemap Styles. These styles use open data from Overture Maps and OpenStreetMap. An ArcGIS access token is required.
esri_open_style( style_name, variant = NULL, token = NULL, language = NULL, worldview = NULL, places = NULL )esri_open_style( style_name, variant = NULL, token = NULL, language = NULL, worldview = NULL, places = NULL )
style_name |
The name of the style. Available styles: "osm-style", "osm-style-relief", "navigation", "navigation-dark", "streets", "streets-relief", "streets-night", "hybrid", "light-gray", "dark-gray", "blueprint". |
variant |
An optional variant for the style. Not all styles support variants. Use the style table in Details to see which variants are available. |
token |
An ArcGIS access token (character) or an |
language |
An optional language code for map labels (e.g., "fr", "zh-CN"). |
worldview |
An optional worldview for boundary representation. |
places |
An optional POI visibility setting: "all", "attributed", or "none". |
The following styles and variant options are available:
| Style | Variants |
| osm-style | (none) |
| osm-style-relief | base |
| navigation | (none) |
| navigation-dark | (none) |
| streets | (none) |
| streets-relief | base |
| streets-night | (none) |
| hybrid | detail |
| light-gray | base, labels |
| dark-gray | base, labels |
| blueprint | (none) |
A style URL string for use with maplibre.
## Not run: # Basic usage maplibre(style = esri_open_style("streets")) # With a variant maplibre(style = esri_open_style("light-gray", variant = "labels")) # Dark navigation style maplibre(style = esri_open_style("navigation-dark")) ## End(Not run)## Not run: # Basic usage maplibre(style = esri_open_style("streets")) # With a variant maplibre(style = esri_open_style("light-gray", variant = "labels")) # Dark navigation style maplibre(style = esri_open_style("navigation-dark")) ## End(Not run)
Generates a style URL for the ArcGIS Basemap Styles Service (v2). These styles use authoritative Esri data sources (TomTom, Garmin, USGS, etc.). An ArcGIS access token is required.
esri_style( style_name, variant = NULL, token = NULL, language = NULL, worldview = NULL, places = NULL )esri_style( style_name, variant = NULL, token = NULL, language = NULL, worldview = NULL, places = NULL )
style_name |
The name of the style. Available styles: "navigation", "navigation-night", "streets", "streets-night", "streets-relief", "community", "outdoor", "topographic", "terrain", "imagery", "light-gray", "dark-gray", "oceans", "hillshade", "human-geography", "human-geography-dark", "charted-territory", "colored-pencil", "nova", "modern-antique", "midcentury", "newspaper". |
variant |
An optional variant for the style. Not all styles support variants. Use the style table in Details to see which variants are available. |
token |
An ArcGIS access token (character) or an |
language |
An optional language code for map labels (e.g., "fr", "zh-CN"). |
worldview |
An optional worldview for boundary representation. |
places |
An optional POI visibility setting: "all", "attributed", or "none". |
The following styles and variant options are available:
| Style | Variants |
| navigation | (none) |
| navigation-night | (none) |
| streets | (none) |
| streets-night | (none) |
| streets-relief | base |
| community | (none) |
| outdoor | (none) |
| topographic | base |
| terrain | base, detail |
| imagery | standard, labels |
| light-gray | base, labels |
| dark-gray | base, labels |
| oceans | base, labels |
| hillshade | light, dark |
| human-geography | base, detail, labels |
| human-geography-dark | base, detail, labels |
| charted-territory | base |
| colored-pencil | (none) |
| nova | (none) |
| modern-antique | base |
| midcentury | (none) |
| newspaper | (none) |
A style URL string for use with maplibre.
## Not run: # Basic usage maplibre(style = esri_style("streets")) # With a variant maplibre(style = esri_style("topographic", variant = "base")) # With language and places maplibre(style = esri_style("navigation", language = "fr", places = "all")) ## End(Not run)## Not run: # Basic usage maplibre(style = esri_style("streets")) # With a variant maplibre(style = esri_style("topographic", variant = "base")) # With language and places maplibre(style = esri_style("navigation", language = "fr", places = "all")) ## End(Not run)
Fit the map to a bounding box
fit_bounds(map, bbox, animate = FALSE, ...)fit_bounds(map, bbox, animate = FALSE, ...)
map |
A map object created by the |
bbox |
A bounding box specified as a numeric vector of length 4 (minLng, minLat, maxLng, maxLat), or an sf object from which a bounding box will be calculated. |
animate |
A logical value indicating whether to animate the transition to the new bounds. Defaults to FALSE. |
... |
Additional named arguments for fitting the bounds. |
The updated map object.
Returns the FlowMapGL 9.3.0 preset color scheme names supported by
add_flowmap(). These names are case-sensitive.
flowmap_color_schemes()flowmap_color_schemes()
The bundled FlowMapGL presets are:
Blues, BluGrn, BluYl, BrwnYl, BuGn, BuPu, Burg, BurgYl, Cool, DarkMint, Emrld, GnBu, Grayish, Greens, Greys, Inferno, Magenta, Magma, Mint, Oranges, OrRd, OrYel, Peach, Plasma, PinkYl, PuBu, PuBuGn, PuRd, Purp, Purples, PurpOr, RdPu, RedOr, Reds, Sunset, SunsetDark, Teal, TealGrn, Viridis, Warm, YlGn, YlGnBu, YlOrBr, and YlOrRd.
A character vector of FlowMapGL preset names.
flowmap_color_schemes()flowmap_color_schemes()
Fly to a given view
fly_to(map, center, zoom = NULL, ...)fly_to(map, center, zoom = NULL, ...)
map |
A map object created by the |
center |
A numeric vector of length 2 specifying the target center of the map (longitude, latitude). |
zoom |
The target zoom level. |
... |
Additional named arguments for flying to the view. |
The updated map object.
This function returns a an expression to get a specified column from a dataset (or a property from a layer).
get_column(column)get_column(column)
column |
The name of the column or property to get. |
A list representing the expression to get the column.
Get drawn features from the map
get_drawn_features(map)get_drawn_features(map)
map |
A map object created by the |
In non-Shiny sessions, retrieval requires a map that was built by piping the
original widget object through add_draw_control(). Non-Shiny proxy updates
and compare widgets are not yet supported.
An sf object containing the drawn features. Feature properties are
preserved as columns and the CRS is EPSG:4326. If the drawn features do not
include an id property, an integer id column is added. If no features are
available, a 0-row sf object with an id column is returned.
## Not run: # In a Shiny application library(shiny) library(mapgl) ui <- fluidPage( mapboxglOutput("map"), actionButton("get_features", "Get Drawn Features"), verbatimTextOutput("feature_output") ) server <- function(input, output, session) { output$map <- renderMapboxgl({ mapboxgl( style = mapbox_style("streets"), center = c(-74.50, 40), zoom = 9 ) |> add_draw_control() }) observeEvent(input$get_features, { drawn_features <- get_drawn_features(mapboxgl_proxy("map")) output$feature_output <- renderPrint({ print(drawn_features) }) }) } shinyApp(ui, server) ## End(Not run)## Not run: # In a Shiny application library(shiny) library(mapgl) ui <- fluidPage( mapboxglOutput("map"), actionButton("get_features", "Get Drawn Features"), verbatimTextOutput("feature_output") ) server <- function(input, output, session) { output$map <- renderMapboxgl({ mapboxgl( style = mapbox_style("streets"), center = c(-74.50, 40), zoom = 9 ) |> add_draw_control() }) observeEvent(input$get_features, { drawn_features <- get_drawn_features(mapboxgl_proxy("map")) output$feature_output <- renderPrint({ print(drawn_features) }) }) } shinyApp(ui, server) ## End(Not run)
This function retrieves the results of a feature query triggered by query_rendered_features().
It returns the features as a deduplicated sf object. Note that only features that were
visible in the viewport at the time of the query will be included.
get_queried_features(map)get_queried_features(map)
map |
A map object (mapboxgl, maplibre) or proxy object (mapboxgl_proxy, maplibre_proxy, mapboxgl_compare_proxy, maplibre_compare_proxy) |
An sf object containing the queried features, or an empty sf object if no features were found
## Not run: # In a Shiny server function: observeEvent(input$query_button, { proxy <- maplibre_proxy("map") query_rendered_features(proxy, layer_id = "counties") features <- get_queried_features(proxy) print(nrow(features)) }) ## End(Not run)## Not run: # In a Shiny server function: observeEvent(input$query_button, { proxy <- maplibre_proxy("map") query_rendered_features(proxy, layer_id = "counties") features <- get_queried_features(proxy) print(nrow(features)) }) ## End(Not run)
This function generates an interpolation expression that can be used to style your data.
interpolate( column = NULL, property = NULL, type = "linear", values, stops, na_color = NULL )interpolate( column = NULL, property = NULL, type = "linear", values, stops, na_color = NULL )
column |
The name of the column to use for the interpolation. If specified, |
property |
The name of the property to use for the interpolation. If specified, |
type |
The interpolation type. Can be one of |
values |
A numeric vector of values at which stops occur. |
stops |
A vector of corresponding stops (colors, sizes, etc.) for the interpolation. |
na_color |
The color to use for missing values. Mapbox GL JS defaults to black if this is not supplied. |
A list representing the interpolation expression.
interpolate( column = "estimate", type = "linear", values = c(1000, 200000), stops = c("#eff3ff", "#08519c") )interpolate( column = "estimate", type = "linear", values = c(1000, 200000), stops = c("#eff3ff", "#08519c") )
This function creates an interpolation expression by automatically calculating break points using different methods and applying a color palette. It handles the values/stops matching automatically and supports the same classification methods as the step functions.
interpolate_palette( data = NULL, column, data_values = NULL, method = "equal", n = 5, palette = NULL, colors = NULL, na_color = "grey", color_ramps = NULL, selected_ramp = NULL )interpolate_palette( data = NULL, column, data_values = NULL, method = "equal", n = 5, palette = NULL, colors = NULL, na_color = "grey", color_ramps = NULL, selected_ramp = NULL )
data |
A data frame or sf object containing the data. If provided, data_values
will be extracted from |
column |
The name of the column to use for the interpolation. |
data_values |
A numeric vector of the actual data values used to calculate breaks.
If NULL and data is provided, will be extracted from |
method |
The method for calculating breaks. Options are "equal" (equal intervals), "quantile" (quantile breaks), or "jenks" (Jenks natural breaks). Defaults to "equal". |
n |
The number of break points to create. Defaults to 5. |
palette |
A function that takes n and returns a character vector of colors.
If NULL and colors is also NULL, defaults to |
colors |
A character vector of colors to use. If provided, these colors will be interpolated to match the number of breaks if needed. Either palette or colors should be provided, but not both. |
na_color |
The color to use for missing values. Defaults to "grey". |
color_ramps |
Optional list of color vectors for downstream legend color-ramp pickers. Ramps are interpolated to the calculated breaks. Named lists use the names as picker labels; unnamed lists get generated labels. |
selected_ramp |
Optional name or index of the initially selected ramp. |
A list of class "mapgl_continuous_scale" containing the interpolation expression and metadata.
## Not run: # Create continuous color scale - using palette function my_data <- data.frame(value = c(10, 25, 30, 45, 60, 75, 90)) scale1 <- interpolate_palette(data = my_data, column = "value", method = "equal", n = 5, palette = viridisLite::plasma) # Using specific colors (will interpolate to 5 if needed) scale2 <- interpolate_palette(data = my_data, column = "value", method = "equal", n = 5, colors = c("red", "yellow", "blue")) # Or with piping scale3 <- my_data |> interpolate_palette("value", method = "equal", n = 5) # Use in a layer add_fill_layer(map, fill_color = scale1$expression) # Extract legend information labels <- get_legend_labels(scale1, format = "currency") colors <- scale1$colors ## End(Not run)## Not run: # Create continuous color scale - using palette function my_data <- data.frame(value = c(10, 25, 30, 45, 60, 75, 90)) scale1 <- interpolate_palette(data = my_data, column = "value", method = "equal", n = 5, palette = viridisLite::plasma) # Using specific colors (will interpolate to 5 if needed) scale2 <- interpolate_palette(data = my_data, column = "value", method = "equal", n = 5, colors = c("red", "yellow", "blue")) # Or with piping scale3 <- my_data |> interpolate_palette("value", method = "equal", n = 5) # Use in a layer add_fill_layer(map, fill_color = scale1$expression) # Extract legend information labels <- get_legend_labels(scale1, format = "currency") colors <- scale1$colors ## End(Not run)
Jump to a given view
jump_to(map, center, zoom = NULL, ...)jump_to(map, center, zoom = NULL, ...)
map |
A map object created by the |
center |
A numeric vector of length 2 specifying the target center of the map (longitude, latitude). |
zoom |
The target zoom level. |
... |
Additional named arguments for jumping to the view. |
The updated map object.
This function creates a styling object that can be passed to legend functions to customize the appearance of legends, including colors, fonts, borders, and shadows.
legend_style( background_color = NULL, background_opacity = NULL, border_color = NULL, border_width = NULL, border_radius = NULL, text_color = NULL, text_size = NULL, title_color = NULL, title_size = NULL, font_family = NULL, title_font_family = NULL, font_weight = NULL, title_font_weight = NULL, element_border_color = NULL, element_border_width = NULL, shadow = NULL, shadow_color = NULL, shadow_size = NULL, padding = NULL )legend_style( background_color = NULL, background_opacity = NULL, border_color = NULL, border_width = NULL, border_radius = NULL, text_color = NULL, text_size = NULL, title_color = NULL, title_size = NULL, font_family = NULL, title_font_family = NULL, font_weight = NULL, title_font_weight = NULL, element_border_color = NULL, element_border_width = NULL, shadow = NULL, shadow_color = NULL, shadow_size = NULL, padding = NULL )
background_color |
Background color for the legend container (e.g., "white", "#ffffff"). |
background_opacity |
Opacity of the legend background (0-1, where 1 is fully opaque). |
border_color |
Color of the legend border (e.g., "black", "#000000"). |
border_width |
Width of the legend border in pixels. |
border_radius |
Border radius for rounded corners in pixels. |
text_color |
Color of the legend text (e.g., "black", "#000000"). |
text_size |
Size of the legend text in pixels. |
title_color |
Color of the legend title text. |
title_size |
Size of the legend title text in pixels. |
font_family |
Font family for legend text (e.g., "Arial", "Times New Roman", "Open Sans"). |
title_font_family |
Font family for legend title (defaults to font_family if not specified). |
font_weight |
Font weight for legend text (e.g., "normal", "bold", "lighter", or numeric like 400, 700). |
title_font_weight |
Font weight for legend title (defaults to font_weight if not specified). |
element_border_color |
Color for borders around legend elements (color bar for continuous, patches/circles for categorical). |
element_border_width |
Width in pixels for borders around legend elements. |
shadow |
Logical, whether to add a drop shadow to the legend. |
shadow_color |
Color of the drop shadow (e.g., "black", "rgba(0,0,0,0.3)"). |
shadow_size |
Size/blur radius of the drop shadow in pixels. |
padding |
Internal padding of the legend container in pixels. |
A list of class "mapgl_legend_style" containing the styling options.
## Not run: # Create a dark theme legend style dark_style <- legend_style( background_color = "#2c3e50", text_color = "white", title_color = "white", font_family = "Arial", title_font_weight = "bold", element_border_color = "white", element_border_width = 1, shadow = TRUE, shadow_color = "rgba(0,0,0,0.3)", shadow_size = 6 ) # Use the style in a legend add_categorical_legend( map = map, legend_title = "Categories", values = c("A", "B", "C"), colors = c("red", "green", "blue"), style = dark_style ) # Create a minimal style with just borders minimal_style <- legend_style( element_border_color = "gray", element_border_width = 1 ) ## End(Not run)## Not run: # Create a dark theme legend style dark_style <- legend_style( background_color = "#2c3e50", text_color = "white", title_color = "white", font_family = "Arial", title_font_weight = "bold", element_border_color = "white", element_border_width = 1, shadow = TRUE, shadow_color = "rgba(0,0,0,0.3)", shadow_size = 6 ) # Use the style in a legend add_categorical_legend( map = map, legend_title = "Categories", values = c("A", "B", "C"), colors = c("red", "green", "blue"), style = dark_style ) # Create a minimal style with just borders minimal_style <- legend_style( element_border_color = "gray", element_border_width = 1 ) ## End(Not run)
These functions add categorical and continuous legends to maps. Use legend_style()
to customize appearance and clear_legend() to remove legends.
add_legend( map, legend_title, values = NULL, colors = NULL, type = c("continuous", "categorical"), circular_patches = FALSE, patch_shape = "square", position = "top-left", sizes = NULL, add = FALSE, unique_id = NULL, width = NULL, layer_id = NULL, margin_top = NULL, margin_right = NULL, margin_bottom = NULL, margin_left = NULL, style = NULL, target = NULL, interactive = FALSE, filter_column = NULL, filter_values = NULL, classification = NULL, breaks = NULL, color_ramps = NULL, selected_ramp = NULL, ramp_picker = !is.null(color_ramps), ramp_labels = TRUE, color_column = NULL, color_property = NULL, na_color = NULL, draggable = FALSE, collapsible = FALSE, collapsed = FALSE ) add_categorical_legend( map, legend_title, values, colors, circular_patches = FALSE, patch_shape = "square", position = "top-left", unique_id = NULL, sizes = NULL, add = FALSE, width = NULL, layer_id = NULL, margin_top = NULL, margin_right = NULL, margin_bottom = NULL, margin_left = NULL, style = NULL, interactive = FALSE, filter_column = NULL, filter_values = NULL, breaks = NULL, draggable = FALSE, collapsible = FALSE, collapsed = FALSE ) add_continuous_legend( map, legend_title, values, colors, position = "top-left", unique_id = NULL, add = FALSE, width = NULL, layer_id = NULL, margin_top = NULL, margin_right = NULL, margin_bottom = NULL, margin_left = NULL, style = NULL, interactive = FALSE, filter_column = NULL, filter_values = NULL, draggable = FALSE, color_ramps = NULL, selected_ramp = NULL, ramp_picker = !is.null(color_ramps), ramp_labels = TRUE, color_column = NULL, color_property = NULL, na_color = NULL, collapsible = FALSE, collapsed = FALSE ) ## S3 method for class 'mapboxgl_compare' add_legend( map, legend_title, values, colors, type = c("continuous", "categorical"), circular_patches = FALSE, patch_shape = "square", position = "top-left", sizes = NULL, add = FALSE, unique_id = NULL, width = NULL, layer_id = NULL, margin_top = NULL, margin_right = NULL, margin_bottom = NULL, margin_left = NULL, style = NULL, target = "compare", interactive = FALSE, filter_column = NULL, filter_values = NULL, classification = NULL, breaks = NULL, color_ramps = NULL, selected_ramp = NULL, ramp_picker = !is.null(color_ramps), ramp_labels = TRUE, color_column = NULL, color_property = NULL, na_color = NULL, draggable = FALSE, collapsible = FALSE, collapsed = FALSE ) ## S3 method for class 'maplibre_compare' add_legend( map, legend_title, values, colors, type = c("continuous", "categorical"), circular_patches = FALSE, patch_shape = "square", position = "top-left", sizes = NULL, add = FALSE, unique_id = NULL, width = NULL, layer_id = NULL, margin_top = NULL, margin_right = NULL, margin_bottom = NULL, margin_left = NULL, style = NULL, target = "compare", interactive = FALSE, filter_column = NULL, filter_values = NULL, classification = NULL, breaks = NULL, color_ramps = NULL, selected_ramp = NULL, ramp_picker = !is.null(color_ramps), ramp_labels = TRUE, color_column = NULL, color_property = NULL, na_color = NULL, draggable = FALSE, collapsible = FALSE, collapsed = FALSE )add_legend( map, legend_title, values = NULL, colors = NULL, type = c("continuous", "categorical"), circular_patches = FALSE, patch_shape = "square", position = "top-left", sizes = NULL, add = FALSE, unique_id = NULL, width = NULL, layer_id = NULL, margin_top = NULL, margin_right = NULL, margin_bottom = NULL, margin_left = NULL, style = NULL, target = NULL, interactive = FALSE, filter_column = NULL, filter_values = NULL, classification = NULL, breaks = NULL, color_ramps = NULL, selected_ramp = NULL, ramp_picker = !is.null(color_ramps), ramp_labels = TRUE, color_column = NULL, color_property = NULL, na_color = NULL, draggable = FALSE, collapsible = FALSE, collapsed = FALSE ) add_categorical_legend( map, legend_title, values, colors, circular_patches = FALSE, patch_shape = "square", position = "top-left", unique_id = NULL, sizes = NULL, add = FALSE, width = NULL, layer_id = NULL, margin_top = NULL, margin_right = NULL, margin_bottom = NULL, margin_left = NULL, style = NULL, interactive = FALSE, filter_column = NULL, filter_values = NULL, breaks = NULL, draggable = FALSE, collapsible = FALSE, collapsed = FALSE ) add_continuous_legend( map, legend_title, values, colors, position = "top-left", unique_id = NULL, add = FALSE, width = NULL, layer_id = NULL, margin_top = NULL, margin_right = NULL, margin_bottom = NULL, margin_left = NULL, style = NULL, interactive = FALSE, filter_column = NULL, filter_values = NULL, draggable = FALSE, color_ramps = NULL, selected_ramp = NULL, ramp_picker = !is.null(color_ramps), ramp_labels = TRUE, color_column = NULL, color_property = NULL, na_color = NULL, collapsible = FALSE, collapsed = FALSE ) ## S3 method for class 'mapboxgl_compare' add_legend( map, legend_title, values, colors, type = c("continuous", "categorical"), circular_patches = FALSE, patch_shape = "square", position = "top-left", sizes = NULL, add = FALSE, unique_id = NULL, width = NULL, layer_id = NULL, margin_top = NULL, margin_right = NULL, margin_bottom = NULL, margin_left = NULL, style = NULL, target = "compare", interactive = FALSE, filter_column = NULL, filter_values = NULL, classification = NULL, breaks = NULL, color_ramps = NULL, selected_ramp = NULL, ramp_picker = !is.null(color_ramps), ramp_labels = TRUE, color_column = NULL, color_property = NULL, na_color = NULL, draggable = FALSE, collapsible = FALSE, collapsed = FALSE ) ## S3 method for class 'maplibre_compare' add_legend( map, legend_title, values, colors, type = c("continuous", "categorical"), circular_patches = FALSE, patch_shape = "square", position = "top-left", sizes = NULL, add = FALSE, unique_id = NULL, width = NULL, layer_id = NULL, margin_top = NULL, margin_right = NULL, margin_bottom = NULL, margin_left = NULL, style = NULL, target = "compare", interactive = FALSE, filter_column = NULL, filter_values = NULL, classification = NULL, breaks = NULL, color_ramps = NULL, selected_ramp = NULL, ramp_picker = !is.null(color_ramps), ramp_labels = TRUE, color_column = NULL, color_property = NULL, na_color = NULL, draggable = FALSE, collapsible = FALSE, collapsed = FALSE )
map |
A map object created by the |
legend_title |
The title of the legend. |
values |
The values being represented on the map (either a vector of categories or a vector of stops). |
colors |
The corresponding colors for the values (either a vector of colors, a single color, or an interpolate function). |
type |
One of "continuous" or "categorical" (for |
circular_patches |
(Deprecated) Logical, whether to use circular patches in the legend. Use |
patch_shape |
Character or sf object, the shape of patches to use in categorical legends. Can be one of the built-in shapes ("square", "circle", "line", "hexagon"), a custom SVG string, or an sf object with POLYGON or MULTIPOLYGON geometry (which will be automatically converted to SVG). Default is "square". |
position |
The position of the legend on the map (one of "top-left", "bottom-left", "top-right", "bottom-right"). |
sizes |
An optional numeric vector of sizes for the legend patches, or a single numeric value (only for categorical legends). For line patches, this controls the line thickness. |
add |
Logical, whether to add this legend to existing legends (TRUE) or replace existing legends (FALSE). Default is FALSE. |
unique_id |
Optional. A unique identifier for the legend. If not provided, a random ID will be generated. |
width |
The width of the legend. Can be specified in pixels (e.g., "250px") or as "auto". Default is NULL, which uses the built-in default. |
layer_id |
The ID of the layer (or a character vector of layer IDs) that this legend is associated with. If provided, the legend will be shown/hidden when the layer visibility is toggled. When multiple layer IDs are provided with |
margin_top |
Custom top margin in pixels, allowing for fine control over legend positioning. Default is NULL (uses standard positioning). |
margin_right |
Custom right margin in pixels. Default is NULL. |
margin_bottom |
Custom bottom margin in pixels. Default is NULL. |
margin_left |
Custom left margin in pixels. Default is NULL. |
style |
Optional styling options created by |
target |
For compare objects only: where to place the legend. Can be "compare" (attached to compare container, persists during swipe), "before" (attached to left/top map), or "after" (attached to right/bottom map). Default is "compare". |
interactive |
Logical, whether to make the legend interactive. For categorical legends, clicking on legend items will toggle the visibility of the corresponding features. For continuous legends, a range slider will appear allowing users to filter features by value. Default is FALSE. Note: interactive legends are not yet supported for compare maps. |
filter_column |
Character, the name of the data column to use for filtering when interactive is TRUE. If NULL (default), the column will be auto-detected from the layer's paint expression. |
filter_values |
For interactive legends, the actual data values to filter on. For categorical legends, use this when your display labels differ from the data values (e.g., values = c("Music", "Bar") for display, filter_values = c("music", "bar") for filtering). For continuous legends, provide numeric break values when using formatted display labels (e.g., values = get_legend_labels(scale), filter_values = get_breaks(scale)). If NULL (default), uses values. |
classification |
A mapgl_classification object (from step_quantile, step_equal_interval, etc.) to use for the legend. When provided, values and colors will be automatically extracted. For interactive legends, range-based filtering will be used based on the classification breaks. |
breaks |
Numeric vector of break points for filtering with classification-based legends. Typically extracted automatically from the classification object. Only needed if you want to override the default breaks. |
color_ramps |
For continuous legends, a list of color vectors to expose in a color-ramp picker. Named lists use the names as picker labels; unnamed lists get generated labels. |
selected_ramp |
The initially selected ramp name or index when |
ramp_picker |
Logical, whether to show the continuous legend color-ramp picker. |
ramp_labels |
Logical, whether to show palette labels in the color-ramp picker. |
color_column |
Character, the data column to use when restyling the layer. If NULL, mapgl attempts to auto-detect it from the layer paint expression. |
color_property |
Character, the paint property to restyle. If NULL, mapgl attempts to auto-detect one of |
na_color |
Color to use for missing values when rebuilding the interpolation expression. |
draggable |
Logical, whether the legend can be dragged to a new position by the user. Default is FALSE. |
collapsible |
Logical, whether to render a toggle button that collapses the legend to a header-only view. Default is FALSE. Most useful for categorical legends with tall bodies on small viewports. |
collapsed |
Logical, whether the legend starts in the collapsed state. Only applies when |
Collapsible legends. When collapsible = TRUE, a 26x26px toggle
button is rendered in the legend's top-right corner. Collapsed, only the
title heading and the toggle button remain visible; every other direct
child of the legend (subtitles, swatches, item labels, the reset-filter
button from interactive legends, any user-appended source footers) is
hidden via CSS. The toggle button inherits border_color and
text_color from legend_style() so it picks up your
legend theme.
If you inject your own title block via htmlwidgets::onRender() –
for example, to add a styled heading above the default title – mark that
element with class="mapgl-legend-title" so it stays visible when
collapsed.
The updated map object with the legend added.
## Not run: # Basic categorical legend add_legend(map, "Population", values = c("Low", "Medium", "High"), colors = c("blue", "yellow", "red"), type = "categorical") # Continuous legend with custom styling add_legend(map, "Income", values = c(0, 50000, 100000), colors = c("blue", "yellow", "red"), type = "continuous", style = list( background_color = "white", background_opacity = 0.9, border_width = 2, border_color = "navy", text_color = "darkblue", font_family = "Times New Roman", title_font_weight = "bold" )) # Legend with custom styling using a list add_legend(map, "Temperature", values = c(0, 50, 100), colors = c("blue", "yellow", "red"), type = "continuous", style = list( background_color = "#f0f0f0", title_size = 16, text_size = 12, shadow = TRUE, shadow_color = "rgba(0,0,0,0.1)", shadow_size = 8 )) # Dark legend with white element borders add_legend(map, "Elevation", values = c(0, 1000, 2000, 3000), colors = c("#2c7bb6", "#abd9e9", "#fdae61", "#d7191c"), type = "continuous", style = list( background_color = "#2c3e50", text_color = "white", title_color = "white", element_border_color = "white", element_border_width = 1 )) # Categorical legend with circular patches add_categorical_legend( map = map, legend_title = "Population", values = c("Low", "Medium", "High"), colors = c("#FED976", "#FEB24C", "#FD8D3C"), patch_shape = "circle", sizes = c(10, 15, 20), style = list( background_opacity = 0.95, border_width = 1, border_color = "gray", title_color = "navy", element_border_color = "black", element_border_width = 1 ) ) # Legend with line patches for line layers add_categorical_legend( map = map, legend_title = "Road Type", values = c("Highway", "Primary", "Secondary"), colors = c("#000000", "#333333", "#666666"), patch_shape = "line", sizes = c(5, 3, 1) # Line thickness in pixels ) # Legend with hexagon patches (e.g., for H3 data) add_categorical_legend( map = map, legend_title = "H3 Hexagon Categories", values = c("Urban", "Suburban", "Rural"), colors = c("#8B0000", "#FF6347", "#90EE90"), patch_shape = "hexagon", sizes = 25 ) # Custom SVG shapes - star add_categorical_legend( map = map, legend_title = "Ratings", values = c("5 Star", "4 Star", "3 Star"), colors = c("#FFD700", "#FFA500", "#FF6347"), patch_shape = paste0('<path d="M50,5 L61,35 L95,35 L68,57 L79,91 L50,70 ', 'L21,91 L32,57 L5,35 L39,35 Z" />') ) # Using sf objects directly as patch shapes library(sf) nc <- st_read(system.file("shape/nc.shp", package = "sf")) county_shape <- nc[1, ] # Get first county add_categorical_legend( map = map, legend_title = "County Types", values = c("Rural", "Urban", "Suburban"), colors = c("#228B22", "#8B0000", "#FFD700"), patch_shape = county_shape # sf object automatically converted to SVG ) # For advanced users needing custom conversion options custom_svg <- mapgl:::.sf_to_svg(county_shape, simplify = TRUE, tolerance = 0.001, fit_viewbox = TRUE) add_categorical_legend( map = map, legend_title = "Custom Converted Shape", values = c("Type A"), colors = c("#4169E1"), patch_shape = custom_svg ) # Compare view legends compare_view <- compare(map1, map2) # Add persistent legend (stays visible during swipe) compare_view |> add_legend("Persistent Legend", values = c("Low", "High"), colors = c("blue", "red"), type = "categorical", target = "compare", position = "top-left") # Add legends to specific maps compare_view |> add_legend("Left Map", values = c("A", "B"), colors = c("green", "orange"), type = "categorical", target = "before", position = "bottom-left") |> add_legend("Right Map", values = c("X", "Y"), colors = c("purple", "yellow"), type = "categorical", target = "after", position = "bottom-right") ## End(Not run)## Not run: # Basic categorical legend add_legend(map, "Population", values = c("Low", "Medium", "High"), colors = c("blue", "yellow", "red"), type = "categorical") # Continuous legend with custom styling add_legend(map, "Income", values = c(0, 50000, 100000), colors = c("blue", "yellow", "red"), type = "continuous", style = list( background_color = "white", background_opacity = 0.9, border_width = 2, border_color = "navy", text_color = "darkblue", font_family = "Times New Roman", title_font_weight = "bold" )) # Legend with custom styling using a list add_legend(map, "Temperature", values = c(0, 50, 100), colors = c("blue", "yellow", "red"), type = "continuous", style = list( background_color = "#f0f0f0", title_size = 16, text_size = 12, shadow = TRUE, shadow_color = "rgba(0,0,0,0.1)", shadow_size = 8 )) # Dark legend with white element borders add_legend(map, "Elevation", values = c(0, 1000, 2000, 3000), colors = c("#2c7bb6", "#abd9e9", "#fdae61", "#d7191c"), type = "continuous", style = list( background_color = "#2c3e50", text_color = "white", title_color = "white", element_border_color = "white", element_border_width = 1 )) # Categorical legend with circular patches add_categorical_legend( map = map, legend_title = "Population", values = c("Low", "Medium", "High"), colors = c("#FED976", "#FEB24C", "#FD8D3C"), patch_shape = "circle", sizes = c(10, 15, 20), style = list( background_opacity = 0.95, border_width = 1, border_color = "gray", title_color = "navy", element_border_color = "black", element_border_width = 1 ) ) # Legend with line patches for line layers add_categorical_legend( map = map, legend_title = "Road Type", values = c("Highway", "Primary", "Secondary"), colors = c("#000000", "#333333", "#666666"), patch_shape = "line", sizes = c(5, 3, 1) # Line thickness in pixels ) # Legend with hexagon patches (e.g., for H3 data) add_categorical_legend( map = map, legend_title = "H3 Hexagon Categories", values = c("Urban", "Suburban", "Rural"), colors = c("#8B0000", "#FF6347", "#90EE90"), patch_shape = "hexagon", sizes = 25 ) # Custom SVG shapes - star add_categorical_legend( map = map, legend_title = "Ratings", values = c("5 Star", "4 Star", "3 Star"), colors = c("#FFD700", "#FFA500", "#FF6347"), patch_shape = paste0('<path d="M50,5 L61,35 L95,35 L68,57 L79,91 L50,70 ', 'L21,91 L32,57 L5,35 L39,35 Z" />') ) # Using sf objects directly as patch shapes library(sf) nc <- st_read(system.file("shape/nc.shp", package = "sf")) county_shape <- nc[1, ] # Get first county add_categorical_legend( map = map, legend_title = "County Types", values = c("Rural", "Urban", "Suburban"), colors = c("#228B22", "#8B0000", "#FFD700"), patch_shape = county_shape # sf object automatically converted to SVG ) # For advanced users needing custom conversion options custom_svg <- mapgl:::.sf_to_svg(county_shape, simplify = TRUE, tolerance = 0.001, fit_viewbox = TRUE) add_categorical_legend( map = map, legend_title = "Custom Converted Shape", values = c("Type A"), colors = c("#4169E1"), patch_shape = custom_svg ) # Compare view legends compare_view <- compare(map1, map2) # Add persistent legend (stays visible during swipe) compare_view |> add_legend("Persistent Legend", values = c("Low", "High"), colors = c("blue", "red"), type = "categorical", target = "compare", position = "top-left") # Add legends to specific maps compare_view |> add_legend("Left Map", values = c("A", "B"), colors = c("green", "orange"), type = "categorical", target = "before", position = "bottom-left") |> add_legend("Right Map", values = c("X", "Y"), colors = c("purple", "yellow"), type = "categorical", target = "after", position = "bottom-right") ## End(Not run)
Get Mapbox Style URL
mapbox_style(style_name)mapbox_style(style_name)
style_name |
The name of the style (e.g., "standard", "streets", "outdoors", etc.). |
The style URL corresponding to the given style name.
Initialize a Mapbox GL Map
mapboxgl( style = NULL, center = c(0, 0), zoom = 0, bearing = 0, pitch = 0, projection = "globe", parallels = NULL, access_token = NULL, bounds = NULL, width = "100%", height = NULL, ... )mapboxgl( style = NULL, center = c(0, 0), zoom = 0, bearing = 0, pitch = 0, projection = "globe", parallels = NULL, access_token = NULL, bounds = NULL, width = "100%", height = NULL, ... )
style |
The Mapbox style to use. |
center |
A numeric vector of length 2 specifying the initial center of the map. |
zoom |
The initial zoom level of the map. |
bearing |
The initial bearing (rotation) of the map, in degrees. |
pitch |
The initial pitch (tilt) of the map, in degrees. |
projection |
The map projection to use (e.g., "mercator", "globe"). |
parallels |
A vector of two numbers representing the standard parallels of the projection. Only available when the projection is "albers" or "lambertConformalConic". |
access_token |
Your Mapbox access token. |
bounds |
The bounding box to fit the map to. Accepts one of the following:
|
width |
The width of the output htmlwidget. |
height |
The height of the output htmlwidget. |
... |
Additional named parameters to be passed to the Mapbox GL JS Map. See the Mapbox GL JS documentation for a full list of options: https://docs.mapbox.com/mapbox-gl-js/api/map/#map-parameters. Common options include:
|
An HTML widget for a Mapbox GL map.
## Not run: # Basic map mapboxgl(projection = "globe") # Constrained map with zoom limits and disabled rotation mapboxgl( bounds = my_sf_object, minZoom = 5, maxZoom = 12, dragRotate = FALSE, touchZoomRotate = FALSE ) ## End(Not run)## Not run: # Basic map mapboxgl(projection = "globe") # Constrained map with zoom limits and disabled rotation mapboxgl( bounds = my_sf_object, minZoom = 5, maxZoom = 12, dragRotate = FALSE, touchZoomRotate = FALSE ) ## End(Not run)
This function allows updates to be sent to an existing Mapbox GL Compare widget in a Shiny application.
mapboxgl_compare_proxy( compareId, session = shiny::getDefaultReactiveDomain(), map_side = "before" )mapboxgl_compare_proxy( compareId, session = shiny::getDefaultReactiveDomain(), map_side = "before" )
compareId |
The ID of the compare output element. |
session |
The Shiny session object. |
map_side |
Which map side to target in the compare widget, either "before" or "after". |
A proxy object for the Mapbox GL Compare widget.
This function allows updates to be sent to an existing Mapbox GL map in a Shiny application without redrawing the entire map.
mapboxgl_proxy(mapId, session = shiny::getDefaultReactiveDomain())mapboxgl_proxy(mapId, session = shiny::getDefaultReactiveDomain())
mapId |
The ID of the map output element. |
session |
The Shiny session object. |
A proxy object for the Mapbox GL map.
This function provides a quick way to visualize sf geometries and raster data using Mapbox GL JS. It automatically detects the geometry type and applies appropriate styling.
mapboxgl_view( data, color = "navy", column = NULL, n = NULL, palette = viridisLite::viridis, style = mapbox_style("light"), layer_id = "quickview", legend = TRUE, legend_position = "top-left", interactive_legend = FALSE, ... )mapboxgl_view( data, color = "navy", column = NULL, n = NULL, palette = viridisLite::viridis, style = mapbox_style("light"), layer_id = "quickview", legend = TRUE, legend_position = "top-left", interactive_legend = FALSE, ... )
data |
An sf object, SpatRaster, or RasterLayer to visualize |
color |
The color used to visualize points, lines, or polygons if |
column |
The name of the column to visualize. If NULL (default), geometries are shown with default styling. |
n |
Number of quantile breaks for numeric columns. If specified, uses step_expr() instead of interpolate(). |
palette |
Color palette function that takes n and returns a character vector of colors. Defaults to viridisLite::viridis. |
style |
The Mapbox style to use. Defaults to mapbox_style("light"). |
layer_id |
The layer ID to use for the visualization. Defaults to "quickview". |
legend |
Logical, whether to add a legend when a column is specified. Defaults to TRUE. |
legend_position |
The position of the legend on the map. Defaults to "top-left". |
interactive_legend |
Logical, whether to make the legend interactive. When TRUE, categorical legends allow clicking to toggle visibility, and continuous legends show a range slider. Defaults to FALSE. |
... |
Additional arguments passed to mapboxgl() |
A Mapbox GL map object
## Not run: library(sf) nc <- st_read(system.file("shape/nc.shp", package = "sf")) # Basic view mapboxgl_view(nc) # View with column visualization mapboxgl_view(nc, column = "AREA") # View with quantile breaks mapboxgl_view(nc, column = "AREA", n = 5) # Custom palette examples mapboxgl_view(nc, column = "AREA", palette = viridisLite::mako) mapboxgl_view(nc, column = "AREA", palette = function(n) RColorBrewer::brewer.pal(n, "RdYlBu")) mapboxgl_view(nc, column = "AREA", palette = colorRampPalette(c("red", "white", "blue"))) ## End(Not run)## Not run: library(sf) nc <- st_read(system.file("shape/nc.shp", package = "sf")) # Basic view mapboxgl_view(nc) # View with column visualization mapboxgl_view(nc, column = "AREA") # View with quantile breaks mapboxgl_view(nc, column = "AREA", n = 5) # Custom palette examples mapboxgl_view(nc, column = "AREA", palette = viridisLite::mako) mapboxgl_view(nc, column = "AREA", palette = function(n) RColorBrewer::brewer.pal(n, "RdYlBu")) mapboxgl_view(nc, column = "AREA", palette = colorRampPalette(c("red", "white", "blue"))) ## End(Not run)
Create a Mapbox GL Compare output element for Shiny
mapboxglCompareOutput(outputId, width = "100%", height = "400px")mapboxglCompareOutput(outputId, width = "100%", height = "400px")
outputId |
The output variable to read from |
width |
The width of the element |
height |
The height of the element |
A Mapbox GL Compare output element for use in a Shiny UI
Create a Mapbox GL output element for Shiny
mapboxglOutput(outputId, width = "100%", height = "400px")mapboxglOutput(outputId, width = "100%", height = "400px")
outputId |
The output variable to read from |
width |
The width of the element |
height |
The height of the element |
A Mapbox GL output element for use in a Shiny UI
Initialize a Maplibre GL Map
maplibre( style = carto_style("voyager"), center = c(0, 0), zoom = 0, bearing = 0, pitch = 0, projection = "globe", bounds = NULL, width = "100%", height = NULL, ... )maplibre( style = carto_style("voyager"), center = c(0, 0), zoom = 0, bearing = 0, pitch = 0, projection = "globe", bounds = NULL, width = "100%", height = NULL, ... )
style |
The style JSON to use. |
center |
A numeric vector of length 2 specifying the initial center of the map. |
zoom |
The initial zoom level of the map. |
bearing |
The initial bearing (rotation) of the map, in degrees. |
pitch |
The initial pitch (tilt) of the map, in degrees. |
projection |
The map projection to use (e.g., "mercator", "globe"). |
bounds |
The bounding box to fit the map to. Accepts one of the following:
|
width |
The width of the output htmlwidget. |
height |
The height of the output htmlwidget. |
... |
Additional named parameters to be passed to the MapLibre GL JS Map. See the MapLibre GL JS documentation for a full list of options: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/MapOptions/. Common options include:
|
An HTML widget for a MapLibre GL map.
## Not run: # Basic map maplibre() # Constrained map with zoom limits and disabled rotation maplibre( bounds = my_sf_object, minZoom = 5, maxZoom = 12, dragRotate = FALSE, touchZoomRotate = FALSE ) ## End(Not run)## Not run: # Basic map maplibre() # Constrained map with zoom limits and disabled rotation maplibre( bounds = my_sf_object, minZoom = 5, maxZoom = 12, dragRotate = FALSE, touchZoomRotate = FALSE ) ## End(Not run)
This function allows updates to be sent to an existing Maplibre GL Compare widget in a Shiny application.
maplibre_compare_proxy( compareId, session = shiny::getDefaultReactiveDomain(), map_side = "before" )maplibre_compare_proxy( compareId, session = shiny::getDefaultReactiveDomain(), map_side = "before" )
compareId |
The ID of the compare output element. |
session |
The Shiny session object. |
map_side |
Which map side to target in the compare widget, either "before" or "after". |
A proxy object for the Maplibre GL Compare widget.
This function allows updates to be sent to an existing Maplibre GL map in a Shiny application without redrawing the entire map.
maplibre_proxy(mapId, session = shiny::getDefaultReactiveDomain())maplibre_proxy(mapId, session = shiny::getDefaultReactiveDomain())
mapId |
The ID of the map output element. |
session |
The Shiny session object. |
A proxy object for the Maplibre GL map.
This function provides a quick way to visualize sf geometries and raster data using MapLibre GL JS. It automatically detects the geometry type and applies appropriate styling.
maplibre_view( data, color = "navy", column = NULL, n = NULL, palette = viridisLite::viridis, style = carto_style("positron"), layer_id = "quickview", legend = TRUE, legend_position = "top-left", interactive_legend = FALSE, ... )maplibre_view( data, color = "navy", column = NULL, n = NULL, palette = viridisLite::viridis, style = carto_style("positron"), layer_id = "quickview", legend = TRUE, legend_position = "top-left", interactive_legend = FALSE, ... )
data |
An sf object, SpatRaster, or RasterLayer to visualize |
color |
The color used to visualize points, lines, or polygons if |
column |
The name of the column to visualize. If NULL (default), geometries are shown with default styling. |
n |
Number of quantile breaks for numeric columns. If specified, uses step_expr() instead of interpolate(). |
palette |
Color palette function that takes n and returns a character vector of colors. Defaults to viridisLite::viridis. |
style |
The MapLibre style to use. Defaults to carto_style("positron"). |
layer_id |
The layer ID to use for the visualization. Defaults to "quickview". |
legend |
Logical, whether to add a legend when a column is specified. Defaults to TRUE. |
legend_position |
The position of the legend on the map. Defaults to "top-left". |
interactive_legend |
Logical, whether to make the legend interactive. When TRUE, categorical legends allow clicking to toggle visibility, and continuous legends show a range slider. Defaults to FALSE. |
... |
Additional arguments passed to maplibre() |
A MapLibre GL map object
## Not run: library(sf) nc <- st_read(system.file("shape/nc.shp", package = "sf")) # Basic view maplibre_view(nc) # View with column visualization maplibre_view(nc, column = "AREA") # View with quantile breaks maplibre_view(nc, column = "AREA", n = 5) # Custom palette examples maplibre_view(nc, column = "AREA", palette = viridisLite::mako) maplibre_view(nc, column = "AREA", palette = function(n) RColorBrewer::brewer.pal(n, "RdYlBu")) maplibre_view(nc, column = "AREA", palette = colorRampPalette(c("red", "white", "blue"))) ## End(Not run)## Not run: library(sf) nc <- st_read(system.file("shape/nc.shp", package = "sf")) # Basic view maplibre_view(nc) # View with column visualization maplibre_view(nc, column = "AREA") # View with quantile breaks maplibre_view(nc, column = "AREA", n = 5) # Custom palette examples maplibre_view(nc, column = "AREA", palette = viridisLite::mako) maplibre_view(nc, column = "AREA", palette = function(n) RColorBrewer::brewer.pal(n, "RdYlBu")) maplibre_view(nc, column = "AREA", palette = colorRampPalette(c("red", "white", "blue"))) ## End(Not run)
Create a Maplibre GL Compare output element for Shiny
maplibreCompareOutput(outputId, width = "100%", height = "400px")maplibreCompareOutput(outputId, width = "100%", height = "400px")
outputId |
The output variable to read from |
width |
The width of the element |
height |
The height of the element |
A Maplibre GL Compare output element for use in a Shiny UI
Create a Maplibre GL output element for Shiny
maplibreOutput(outputId, width = "100%", height = "400px")maplibreOutput(outputId, width = "100%", height = "400px")
outputId |
The output variable to read from |
width |
The width of the element |
height |
The height of the element |
A Maplibre GL output element for use in a Shiny UI
Get MapTiler Style URL
maptiler_style(style_name, variant = NULL, api_key = NULL)maptiler_style(style_name, variant = NULL, api_key = NULL)
style_name |
The name of the style (e.g., "basic", "streets", "toner", etc.). |
variant |
The color variant of the style. Options are "dark", "light", or "pastel". Default is NULL (standard variant). Not all styles support all variants. |
api_key |
Your MapTiler API key (required) |
The style URL corresponding to the given style name and variant.
This function generates a match expression that can be used to style your data.
match_expr(column = NULL, property = NULL, values, stops, default = "#cccccc")match_expr(column = NULL, property = NULL, values, stops, default = "#cccccc")
column |
The name of the column to use for the match expression. If specified, |
property |
The name of the property to use for the match expression. If specified, |
values |
A vector of values to match against. |
stops |
A vector of corresponding stops (colors, etc.) for the matched values. |
default |
A default value to use if no matches are found. |
A list representing the match expression.
match_expr( column = "category", values = c("A", "B", "C"), stops = c("#ff0000", "#00ff00", "#0000ff"), default = "#cccccc" )match_expr( column = "category", values = c("A", "B", "C"), stops = c("#ff0000", "#00ff00", "#0000ff"), default = "#cccccc" )
This function allows a layer to be moved to a different z-position in a Mapbox GL or Maplibre GL map. For initial maps, the operation is queued and executed during map initialization. For proxy objects, the operation is executed immediately.
move_layer(map, layer_id, before_id = NULL)move_layer(map, layer_id, before_id = NULL)
map |
A map object created by |
layer_id |
The ID of the layer to move. |
before_id |
The ID of an existing layer to insert the new layer before. Important: this means that the layer will appear immediately behind the layer defined in |
The updated map or proxy object.
This function creates a number formatting expression that formats numeric values according to locale-specific conventions. It can be used in tooltips, popups, and text fields for symbol layers.
number_format( column, locale = "en-US", style = "decimal", currency = NULL, unit = NULL, minimum_fraction_digits = NULL, maximum_fraction_digits = NULL, minimum_integer_digits = NULL, use_grouping = NULL, notation = NULL, compact_display = NULL )number_format( column, locale = "en-US", style = "decimal", currency = NULL, unit = NULL, minimum_fraction_digits = NULL, maximum_fraction_digits = NULL, minimum_integer_digits = NULL, use_grouping = NULL, notation = NULL, compact_display = NULL )
column |
The name of the column containing the numeric value to format. Can also be an expression that evaluates to a number. |
locale |
A string specifying the locale to use for formatting (e.g., "en-US", "de-DE", "fr-FR"). Defaults to "en-US". |
style |
The formatting style to use. Options include:
|
currency |
For style = "currency", the ISO 4217 currency code (e.g., "USD", "EUR", "GBP"). |
unit |
For style = "unit", the unit to use (e.g., "kilometer", "mile", "liter"). |
minimum_fraction_digits |
The minimum number of fraction digits to display. |
maximum_fraction_digits |
The maximum number of fraction digits to display. |
minimum_integer_digits |
The minimum number of integer digits to display. |
use_grouping |
Whether to use grouping separators (e.g., thousands separators). Defaults to TRUE. |
notation |
The formatting notation. Options include:
|
compact_display |
For notation = "compact", whether to use "short" (default) or "long" form. |
A list representing the number-format expression.
# Basic number formatting with thousands separators number_format("population") # Currency formatting number_format("income", style = "currency", currency = "USD") # Percentage with 1 decimal place number_format("rate", style = "percent", maximum_fraction_digits = 1) # Compact notation for large numbers number_format("population", notation = "compact") # Using within a tooltip concat("Population: ", number_format("population", notation = "compact")) # Using with get_column() number_format(get_column("value"), style = "currency", currency = "EUR")# Basic number formatting with thousands separators number_format("population") # Currency formatting number_format("income", style = "currency", currency = "USD") # Percentage with 1 decimal place number_format("rate", style = "percent", maximum_fraction_digits = 1) # Compact notation for large numbers number_format("population", notation = "compact") # Using within a tooltip concat("Population: ", number_format("population", notation = "compact")) # Using with get_column() number_format(get_column("value"), style = "currency", currency = "EUR")
For a given story_section(), you may want to trigger an event when the section becomes visible.
This function wraps shiny::observeEvent() to allow you to modify the state of your map or
invoke other Shiny actions on user scroll.
on_section(map_id, section_id, handler)on_section(map_id, section_id, handler)
map_id |
The ID of your map output |
section_id |
The ID of the section to trigger on, defined in |
handler |
Expression to execute when section becomes visible. |
Get OpenFreeMap Style URL
openfreemap_style(style_name)openfreemap_style(style_name)
style_name |
The name of the style (e.g., "bright", "positron", "liberty", "dark", or "fiord"). |
The style URL corresponding to the given style name.
This function takes an R color palette and converts it into a base64-encoded LUT (Look-Up Table) image that can be used with Mapbox GL JS v3+ for custom map themes. The LUT applies color transformations to the basemap.
palette_to_lut( colors, n = 5, method = c("tint", "replace", "duotone", "tritone", "luminosity"), intensity = 0.5, lut_size = 32, reverse = FALSE )palette_to_lut( colors, n = 5, method = c("tint", "replace", "duotone", "tritone", "luminosity"), intensity = 0.5, lut_size = 32, reverse = FALSE )
colors |
Character vector of colors (hex or R color names) or a function that generates colors (like viridis) |
n |
Number of colors to sample from the palette (if colors is a function) |
method |
Method for applying colors to the LUT:
|
intensity |
Strength of the effect (0-1) |
lut_size |
Size of the LUT (16, 32, or 64) |
reverse |
Logical; whether to reverse the color palette |
Base64-encoded PNG data URI string
## Not run: # Using viridis palette theme_data <- palette_to_lut(viridisLite::viridis(5)) # Using a palette function directly theme_data <- palette_to_lut(viridisLite::plasma, n = 7) # Using RColorBrewer theme_data <- palette_to_lut(RColorBrewer::brewer.pal(9, "YlOrRd")) # Use in mapboxgl (requires Mapbox GL JS v3+) mapboxgl( center = c(139.7, 35.7), zoom = 10, config = list( basemap = list( theme = "custom", "theme-data" = theme_data ) ) ) ## End(Not run)## Not run: # Using viridis palette theme_data <- palette_to_lut(viridisLite::viridis(5)) # Using a palette function directly theme_data <- palette_to_lut(viridisLite::plasma, n = 7) # Using RColorBrewer theme_data <- palette_to_lut(RColorBrewer::brewer.pal(9, "YlOrRd")) # Use in mapboxgl (requires Mapbox GL JS v3+) mapboxgl( center = c(139.7, 35.7), zoom = 10, config = list( basemap = list( theme = "custom", "theme-data" = theme_data ) ) ) ## End(Not run)
Configure popup options
popup_options(template = NULL, theme = "auto", ...)popup_options(template = NULL, theme = "auto", ...)
template |
Template string or a named list with |
theme |
Visual theme: |
... |
Additional properties passed to the Mapbox/MapLibre popup, such as |
Renders a mapgl map as a static PNG image for display. When called inside a
knitr/Quarto document, the map is included as a static figure via
knitr::include_graphics(). In an interactive session, the image is
displayed in the R graphics device.
print_map( map, width = 900, height = 500, include_legend = TRUE, hide_controls = TRUE, include_scale_bar = TRUE, basemap_color = NULL, image_scale = 1, background = "white", delay = NULL )print_map( map, width = 900, height = 500, include_legend = TRUE, hide_controls = TRUE, include_scale_bar = TRUE, basemap_color = NULL, image_scale = 1, background = "white", delay = NULL )
map |
A map object created by |
width |
Integer. The width of the map viewport in pixels. Always
overrides any |
height |
Integer. The height of the map viewport in pixels. Always
overrides any |
include_legend |
Logical. Include the legend in the output? Default
|
hide_controls |
Logical. Hide navigation and other interactive controls?
Default |
include_scale_bar |
Logical. Include the scale bar? Default |
basemap_color |
Character string or |
image_scale |
Numeric. Scale factor for the output image. Use |
background |
Character string or |
delay |
Numeric or |
In a knitr context, the result of knitr::include_graphics().
In an interactive session, the image is displayed and the temporary file
path is returned invisibly.
## Not run: library(mapgl) map <- maplibre( center = c(-96, 37.8), zoom = 3 ) # In a Quarto document chunk print_map(map) # With custom dimensions print_map(map, width = 1200, height = 800, image_scale = 2) ## End(Not run)## Not run: library(mapgl) map <- maplibre( center = c(-96, 37.8), zoom = 3 ) # In a Quarto document chunk print_map(map) # With custom dimensions print_map(map, width = 1200, height = 800, image_scale = 2) ## End(Not run)
This function queries features that are currently rendered (visible) in the map viewport.
Only features within the current viewport bounds will be returned - features outside the
visible area or hidden due to zoom constraints will not be included. Use get_queried_features()
to retrieve the results as an sf object, or use the callback parameter to handle results
automatically when they're ready.
query_rendered_features( proxy, geometry = NULL, layer_id = NULL, filter = NULL, callback = NULL )query_rendered_features( proxy, geometry = NULL, layer_id = NULL, filter = NULL, callback = NULL )
proxy |
A MapboxGL or Maplibre proxy object, defined with |
geometry |
The geometry to query. Can be:
|
layer_id |
A character vector of layer names to include in the query.
Can be a single layer name or multiple layer names. If |
filter |
A filter expression used to filter features in the query. Should be a list
representing a Mapbox GL expression. Using this parameter applies the filter during the
query WITHOUT changing the map display, avoiding race conditions. If you've called
|
callback |
A function to execute when results are ready. The function will receive the sf object as its argument. If provided, this avoids timing issues by automatically handling results when they're available. |
This function only queries features that are currently rendered in the map viewport. Features outside the visible area will not be returned, even if they exist in the data source. This includes features that are:
Outside the current map bounds
Hidden due to zoom level constraints (minzoom/maxzoom)
Not yet loaded (if using vector tiles)
IMPORTANT: set_filter() is asynchronous while query_rendered_features() is synchronous.
Calling query_rendered_features() immediately after set_filter() will return features from the
PREVIOUS filter state, not the new one.
Pattern 1: Query First, Then Filter (Recommended)
query_rendered_features(proxy, layer_id = "counties", callback = function(features) {
# Process features, then update map based on results
proxy |> set_filter("highlight", list("in", "id", features$id))
})
Pattern 2: Use Filter Parameter Instead
# Query with filter without changing map display
query_rendered_features(proxy, filter = list(">=", "population", 1000),
callback = function(features) {
# Process filtered results without race condition
})
# WRONG - This will return stale results!
proxy |> set_filter("layer", new_filter)
query_rendered_features(proxy, layer_id = "layer") # Gets OLD filter results
The proxy object (invisibly). Use get_queried_features() to retrieve the query results manually,
or provide a callback function to handle results automatically.
## Not run: # Pattern 1: Query first, then filter (RECOMMENDED) proxy <- maplibre_proxy("map") query_rendered_features(proxy, layer_id = "counties", callback = function(features) { if (nrow(features) > 0) { # Filter map based on query results - no race condition proxy |> set_filter("selected", list("in", "id", features$id)) } }) # Pattern 2: Use filter parameter to avoid race conditions query_rendered_features(proxy, filter = list(">=", "population", 50000), callback = function(features) { # These results are guaranteed to match the filter print(paste("Found", nrow(features), "high population areas")) }) # Query specific bounding box with callback query_rendered_features(proxy, geometry = c(100, 100, 200, 200), layer_id = "counties", callback = function(features) { print(paste("Found", nrow(features), "features")) }) # ANTI-PATTERN - Don't do this! # proxy |> set_filter("layer", new_filter) # query_rendered_features(proxy, layer_id = "layer") # Will get stale results! ## End(Not run)## Not run: # Pattern 1: Query first, then filter (RECOMMENDED) proxy <- maplibre_proxy("map") query_rendered_features(proxy, layer_id = "counties", callback = function(features) { if (nrow(features) > 0) { # Filter map based on query results - no race condition proxy |> set_filter("selected", list("in", "id", features$id)) } }) # Pattern 2: Use filter parameter to avoid race conditions query_rendered_features(proxy, filter = list(">=", "population", 50000), callback = function(features) { # These results are guaranteed to match the filter print(paste("Found", nrow(features), "high population areas")) }) # Query specific bounding box with callback query_rendered_features(proxy, geometry = c(100, 100, 200, 200), layer_id = "counties", callback = function(features) { print(paste("Found", nrow(features), "features")) }) # ANTI-PATTERN - Don't do this! # proxy |> set_filter("layer", new_filter) # query_rendered_features(proxy, layer_id = "layer") # Will get stale results! ## End(Not run)
Render a Mapbox GL output element in Shiny
renderMapboxgl(expr, env = parent.frame(), quoted = FALSE)renderMapboxgl(expr, env = parent.frame(), quoted = FALSE)
expr |
An expression that generates a Mapbox GL map |
env |
The environment in which to evaluate |
quoted |
Is |
A rendered Mapbox GL map for use in a Shiny server
Render a Mapbox GL Compare output element in Shiny
renderMapboxglCompare(expr, env = parent.frame(), quoted = FALSE)renderMapboxglCompare(expr, env = parent.frame(), quoted = FALSE)
expr |
An expression that generates a Mapbox GL Compare map |
env |
The environment in which to evaluate |
quoted |
Is |
A rendered Mapbox GL Compare map for use in a Shiny server
Render a Maplibre GL output element in Shiny
renderMaplibre(expr, env = parent.frame(), quoted = FALSE)renderMaplibre(expr, env = parent.frame(), quoted = FALSE)
expr |
An expression that generates a Maplibre GL map |
env |
The environment in which to evaluate |
quoted |
Is |
A rendered Maplibre GL map for use in a Shiny server
Render a Maplibre GL Compare output element in Shiny
renderMaplibreCompare(expr, env = parent.frame(), quoted = FALSE)renderMaplibreCompare(expr, env = parent.frame(), quoted = FALSE)
expr |
An expression that generates a Maplibre GL Compare map |
env |
The environment in which to evaluate |
quoted |
Is |
A rendered Maplibre GL Compare map for use in a Shiny server
Renders a mapgl map widget to a static PNG file using headless Chrome
via the chromote package. Uses the same html2canvas-based screenshot
infrastructure as add_screenshot_control().
save_map( map, filename = "map.png", width = 900, height = 500, include_legend = TRUE, hide_controls = TRUE, include_scale_bar = TRUE, basemap_color = NULL, image_scale = 1, background = "white", delay = NULL )save_map( map, filename = "map.png", width = 900, height = 500, include_legend = TRUE, hide_controls = TRUE, include_scale_bar = TRUE, basemap_color = NULL, image_scale = 1, background = "white", delay = NULL )
map |
A map object created by |
filename |
Character string. The output file path. Defaults to
|
width |
Integer. The width of the map viewport in pixels. Always
overrides any |
height |
Integer. The height of the map viewport in pixels. Always
overrides any |
include_legend |
Logical. Include the legend in the output? Default
|
hide_controls |
Logical. Hide navigation and other interactive controls?
Default |
include_scale_bar |
Logical. Include the scale bar? Default |
basemap_color |
Character string or |
image_scale |
Numeric. Scale factor for the output image. Use |
background |
Character string or |
delay |
Numeric or |
This function requires the chromote and httpuv packages.
Install them with install.packages(c("chromote", "httpuv")). chromote
also requires a Chrome or Chromium browser installation.
The function works by:
Saving the map widget to a temporary HTML file
Opening it in headless Chrome
Waiting for all map tiles and styles to load
Using html2canvas to capture the rendered map (including legends, attribution, and optionally the scale bar)
Decoding the captured image and writing it to the output file
The output file path, invisibly.
## Not run: library(mapgl) map <- maplibre( center = c(-96, 37.8), zoom = 3 ) save_map(map, "us_map.png") save_map(map, "us_map_retina.png", image_scale = 2) # Remove basemap, keep only data layers on white save_map(map, "data_only.png", basemap_color = "white") ## End(Not run)## Not run: library(mapgl) map <- maplibre( center = c(-96, 37.8), zoom = 3 ) save_map(map, "us_map.png") save_map(map, "us_map_retina.png", image_scale = 2) # Remove basemap, keep only data layers on white save_map(map, "data_only.png", basemap_color = "white") ## End(Not run)
Set a configuration property for a Mapbox GL map
set_config_property(map, import_id, config_name, value)set_config_property(map, import_id, config_name, value)
map |
A map object created by the |
import_id |
The name of the imported style to set the config for (e.g., 'basemap'). |
config_name |
The name of the configuration property from the style. |
value |
The value to set for the configuration property. |
The updated map object with the configuration property set.
This function sets a filter on a map layer, working with both regular map objects and proxy objects.
set_filter(map, layer_id, filter)set_filter(map, layer_id, filter)
map |
A map object created by the |
layer_id |
The ID of the layer to which the filter will be applied. |
filter |
The filter expression to apply. |
The updated map object.
A layer created via the cluster_options shortcut in add_circle_layer()
or add_symbol_layer() is actually three layers over one source
("id", "id-clusters", "id-cluster-count"). set_filter() targets
exactly one of them, so:
Calling set_filter("id", ...) applies only to the unclustered
sub-layer. Cluster circles still show the pre-filter counts.
Cluster points are synthetic (their only properties are
point_count, cluster_id, etc.), so a filter that reads a
feature property like "year" cannot be meaningfully applied to
the -clusters layer — it would evaluate to FALSE and hide all
clusters.
For the common "filter my data" case on a clustered map, use
set_source() instead. It replaces the source's data and
Mapbox/MapLibre re-cluster automatically:
mapboxgl_proxy("map") |>
set_source(layer_id = "circles", source = filtered())
set_filter() is still the right tool for cluster-aware filters
that read cluster-point properties, e.g. hiding clusters below a
count threshold:
mapboxgl_proxy("map") |>
set_filter("circles-clusters", list(">=", get_column("point_count"), 10))
Updates the filter state of a flowmap layer, including selected locations and time range.
set_flowmap_filter( proxy, id, selected_locations = NULL, location_filter_mode = NULL, selected_time_range = NULL )set_flowmap_filter( proxy, id, selected_locations = NULL, location_filter_mode = NULL, selected_time_range = NULL )
proxy |
A map proxy object. |
id |
The ID of the flowmap layer to update. |
selected_locations |
Optional vector of location IDs to select. |
location_filter_mode |
Optional location filter mode: |
selected_time_range |
Optional vector of two dates for time filtering. |
The modified map proxy.
Updates one setting of a flowmap layer.
set_flowmap_settings(map, id, name, value)set_flowmap_settings(map, id, name, value)
map |
A map object created by |
id |
The ID of the flowmap layer to update. |
name |
The setting name to update. Supported canonical FlowMapGL
setting names are |
value |
The setting value. |
colorScheme accepts the same values as flow_color_scheme in
add_flowmap(): a FlowMapGL preset name, a character vector of at least two
CSS colors, or a mapgl_continuous_scale object from
interpolate_palette(). opacity must be between 0 and 1. fadeAmount
must be between 0 and 100. maxTopFlowsDisplayNum must be positive.
clusteringLevel must be numeric or NULL. flowLinesRenderingMode must
be "straight", "animated-straight", or "curved".
temporalScaleDomain must be "selected" or "all".
flowEndpointsInViewportMode must be "any" or "both". Boolean
settings must be scalar TRUE or FALSE.
The modified map object.
Set fog on a Mapbox GL map
set_fog( map, range = NULL, color = NULL, horizon_blend = NULL, high_color = NULL, space_color = NULL, star_intensity = NULL )set_fog( map, range = NULL, color = NULL, horizon_blend = NULL, high_color = NULL, space_color = NULL, star_intensity = NULL )
map |
A map object created by the |
range |
A numeric vector of length 2 defining the minimum and maximum range of the fog. |
color |
A string specifying the color of the fog. |
horizon_blend |
A number between 0 and 1 controlling the blending of the fog at the horizon. |
high_color |
A string specifying the color of the fog at higher elevations. |
space_color |
A string specifying the color of the fog in space. |
star_intensity |
A number between 0 and 1 controlling the intensity of the stars in the fog. |
The updated map object.
Set a layout property on a map layer
set_layout_property(map, layer_id = NULL, name, value, layer = NULL)set_layout_property(map, layer_id = NULL, name, value, layer = NULL)
map |
A map object created by the |
layer_id |
The ID of the layer to update. |
name |
The name of the layout property to set. |
value |
The value to set the property to. |
layer |
Deprecated. Use |
The updated map object.
Set a paint property on a map layer
set_paint_property(map, layer_id = NULL, name, value, layer = NULL)set_paint_property(map, layer_id = NULL, name, value, layer = NULL)
map |
A map object created by the |
layer_id |
The ID of the layer to update. |
name |
The name of the paint property to set. |
value |
The value to set the property to. |
layer |
Deprecated. Use |
The updated map object.
Set popup on a map layer
set_popup(map, layer_id = NULL, popup, layer = NULL)set_popup(map, layer_id = NULL, popup, layer = NULL)
map |
A map object created by the |
layer_id |
The ID of the layer to update. |
popup |
The name of the popup property or an expression to set. |
layer |
Deprecated. Use |
The updated map object.
This function sets the projection dynamically after map initialization.
set_projection(map, projection)set_projection(map, projection)
map |
A map object created by mapboxgl() or maplibre() functions, or their respective proxy objects |
projection |
A string representing the projection name (e.g., "mercator", "globe", "albers", "equalEarth", etc.) |
The modified map object
Set rain effect on a Mapbox GL map
set_rain( map, density = 0.5, intensity = 1, color = "#a8adbc", opacity = 0.7, center_thinning = 0.57, direction = c(0, 80), droplet_size = c(2.6, 18.2), distortion_strength = 0.7, vignette = 1, vignette_color = "#464646", remove = FALSE )set_rain( map, density = 0.5, intensity = 1, color = "#a8adbc", opacity = 0.7, center_thinning = 0.57, direction = c(0, 80), droplet_size = c(2.6, 18.2), distortion_strength = 0.7, vignette = 1, vignette_color = "#464646", remove = FALSE )
map |
A map object created by the |
density |
A number between 0 and 1 controlling the rain particles density. Default is 0.5. |
intensity |
A number between 0 and 1 controlling the rain particles movement speed. Default is 1. |
color |
A string specifying the color of the rain droplets. Default is "#a8adbc". |
opacity |
A number between 0 and 1 controlling the rain particles opacity. Default is 0.7. |
center_thinning |
A number between 0 and 1 controlling the thinning factor of rain particles from center. Default is 0.57. |
direction |
A numeric vector of length 2 defining the azimuth and polar angles of the rain direction. Default is c(0, 80). |
droplet_size |
A numeric vector of length 2 controlling the rain droplet size (x - normal to direction, y - along direction). Default is c(2.6, 18.2). |
distortion_strength |
A number between 0 and 1 controlling the rain particles screen-space distortion strength. Default is 0.7. |
vignette |
A number between 0 and 1 controlling the screen-space vignette rain tinting effect intensity. Default is 1.0. |
vignette_color |
A string specifying the rain vignette screen-space corners tint color. Default is "#464646". |
remove |
A logical value indicating whether to remove the rain effect. Default is FALSE. |
The updated map object.
## Not run: # Add rain effect with default values mapboxgl(...) |> set_rain() # Add rain effect with custom values mapboxgl( style = mapbox_style("standard"), center = c(24.951528, 60.169573), zoom = 16.8, pitch = 74, bearing = 12.8 ) |> set_rain( density = 0.5, opacity = 0.7, color = "#a8adbc" ) # Remove rain effect (useful in Shiny) map_proxy |> set_rain(remove = TRUE) ## End(Not run)## Not run: # Add rain effect with default values mapboxgl(...) |> set_rain() # Add rain effect with custom values mapboxgl( style = mapbox_style("standard"), center = c(24.951528, 60.169573), zoom = 16.8, pitch = 74, bearing = 12.8 ) |> set_rain( density = 0.5, opacity = 0.7, color = "#a8adbc" ) # Remove rain effect (useful in Shiny) map_proxy |> set_rain(remove = TRUE) ## End(Not run)
Set snow effect on a Mapbox GL map
set_snow( map, density = 0.85, intensity = 1, color = "#ffffff", opacity = 1, center_thinning = 0.4, direction = c(0, 50), flake_size = 0.71, vignette = 0.3, vignette_color = "#ffffff", remove = FALSE )set_snow( map, density = 0.85, intensity = 1, color = "#ffffff", opacity = 1, center_thinning = 0.4, direction = c(0, 50), flake_size = 0.71, vignette = 0.3, vignette_color = "#ffffff", remove = FALSE )
map |
A map object created by the |
density |
A number between 0 and 1 controlling the snow particles density. Default is 0.85. |
intensity |
A number between 0 and 1 controlling the snow particles movement speed. Default is 1.0. |
color |
A string specifying the color of the snow particles. Default is "#ffffff". |
opacity |
A number between 0 and 1 controlling the snow particles opacity. Default is 1.0. |
center_thinning |
A number between 0 and 1 controlling the thinning factor of snow particles from center. Default is 0.4. |
direction |
A numeric vector of length 2 defining the azimuth and polar angles of the snow direction. Default is c(0, 50). |
flake_size |
A number between 0 and 5 controlling the snow flake particle size. Default is 0.71. |
vignette |
A number between 0 and 1 controlling the snow vignette screen-space effect. Default is 0.3. |
vignette_color |
A string specifying the snow vignette screen-space corners tint color. Default is "#ffffff". |
remove |
A logical value indicating whether to remove the snow effect. Default is FALSE. |
The updated map object.
## Not run: # Add snow effect with default values mapboxgl(...) |> set_snow() # Add snow effect with custom values mapboxgl( style = mapbox_style("standard"), center = c(24.951528, 60.169573), zoom = 16.8, pitch = 74, bearing = 12.8 ) |> set_snow( density = 0.85, flake_size = 0.71, color = "#ffffff" ) # Remove snow effect (useful in Shiny) map_proxy |> set_snow(remove = TRUE) ## End(Not run)## Not run: # Add snow effect with default values mapboxgl(...) |> set_snow() # Add snow effect with custom values mapboxgl( style = mapbox_style("standard"), center = c(24.951528, 60.169573), zoom = 16.8, pitch = 74, bearing = 12.8 ) |> set_snow( density = 0.85, flake_size = 0.71, color = "#ffffff" ) # Remove snow effect (useful in Shiny) map_proxy |> set_snow(remove = TRUE) ## End(Not run)
Set source of a map layer
set_source(map, layer_id = NULL, source, layer = NULL)set_source(map, layer_id = NULL, source, layer = NULL)
map |
A map object created by the |
layer_id |
The ID of the layer to update. |
source |
An sf object (which will be converted to a GeoJSON source). |
layer |
Deprecated. Use |
The updated map object.
Update the style of a map
set_style(map, style, config = NULL, diff = TRUE, preserve_layers = TRUE)set_style(map, style, config = NULL, diff = TRUE, preserve_layers = TRUE)
map |
A map object created by the |
style |
The new style URL to be applied to the map. |
config |
A named list of options to be passed to the style config. |
diff |
A boolean that attempts a diff-based update rather than re-drawing the full style. Not available for all styles. |
preserve_layers |
A boolean that indicates whether to preserve user-added sources and layers when changing styles. Defaults to TRUE. |
The modified map object.
## Not run: map <- mapboxgl( style = mapbox_style("streets"), center = c(-74.006, 40.7128), zoom = 10, access_token = "your_mapbox_access_token" ) # Update the map style in a Shiny app observeEvent(input$change_style, { mapboxgl_proxy("map", session) %>% set_style(mapbox_style("dark"), config = list(showLabels = FALSE), diff = TRUE) }) ## End(Not run)## Not run: map <- mapboxgl( style = mapbox_style("streets"), center = c(-74.006, 40.7128), zoom = 10, access_token = "your_mapbox_access_token" ) # Update the map style in a Shiny app observeEvent(input$change_style, { mapboxgl_proxy("map", session) %>% set_style(mapbox_style("dark"), config = list(showLabels = FALSE), diff = TRUE) }) ## End(Not run)
Set terrain properties on a map
set_terrain(map, source, exaggeration = 1)set_terrain(map, source, exaggeration = 1)
map |
A map object created by the |
source |
The ID of the raster DEM source. |
exaggeration |
The terrain exaggeration factor. |
The modified map object with the terrain settings applied.
## Not run: library(mapgl) mapboxgl( style = mapbox_style("standard-satellite"), center = c(-114.26608, 32.7213), zoom = 14, pitch = 80, bearing = 41 ) |> add_raster_dem_source( id = "mapbox-dem", url = "mapbox://mapbox.mapbox-terrain-dem-v1", tileSize = 512, maxzoom = 14 ) |> set_terrain( source = "mapbox-dem", exaggeration = 1.5 ) ## End(Not run)## Not run: library(mapgl) mapboxgl( style = mapbox_style("standard-satellite"), center = c(-114.26608, 32.7213), zoom = 14, pitch = 80, bearing = 41 ) |> add_raster_dem_source( id = "mapbox-dem", url = "mapbox://mapbox.mapbox-terrain-dem-v1", tileSize = 512, maxzoom = 14 ) |> set_terrain( source = "mapbox-dem", exaggeration = 1.5 ) ## End(Not run)
Set tooltip on a map layer
set_tooltip(map, layer_id = NULL, tooltip, layer = NULL)set_tooltip(map, layer_id = NULL, tooltip, layer = NULL)
map |
A map object created by the |
layer_id |
The ID of the layer to update. |
tooltip |
The name of the tooltip to set. |
layer |
Deprecated. Use |
The updated map object.
Set the map center and zoom level
set_view(map, center, zoom)set_view(map, center, zoom)
map |
A map object created by the |
center |
A numeric vector of length 2 specifying the center of the map (longitude, latitude). |
zoom |
The zoom level. |
The updated map object.
These functions create step expressions using different classification methods, similar to choropleth mapping in GIS software. They automatically calculate break points and generate appropriate step expressions for styling map layers.
step_equal_interval( data = NULL, column, data_values = NULL, n = 5, palette = NULL, colors = NULL, na_color = "grey" ) step_quantile( data = NULL, column, data_values = NULL, n = 5, palette = NULL, colors = NULL, na_color = "grey" ) step_jenks( data = NULL, column, data_values = NULL, n = 5, palette = NULL, colors = NULL, na_color = "grey" )step_equal_interval( data = NULL, column, data_values = NULL, n = 5, palette = NULL, colors = NULL, na_color = "grey" ) step_quantile( data = NULL, column, data_values = NULL, n = 5, palette = NULL, colors = NULL, na_color = "grey" ) step_jenks( data = NULL, column, data_values = NULL, n = 5, palette = NULL, colors = NULL, na_color = "grey" )
data |
A data frame or sf object containing the data. If provided, data_values
will be extracted from |
column |
The name of the column to use for the step expression. |
data_values |
A numeric vector of the actual data values used to calculate breaks.
If NULL and data is provided, will be extracted from |
n |
The number of classes/intervals to create. Defaults to 5. |
palette |
A function that takes n and returns a character vector of colors.
If NULL and colors is also NULL, defaults to |
colors |
A character vector of colors to use. Must have exactly n colors for step classification functions. Either palette or colors should be provided, but not both. |
na_color |
The color to use for missing values. Defaults to "grey". |
Creates equal interval breaks by dividing the data range into equal parts
Creates quantile breaks ensuring approximately equal numbers of observations in each class
Creates Jenks natural breaks using Fisher-Jenks optimization to minimize within-class variance
A list of class "mapgl_classification" containing the step expression and metadata.
interpolate_palette() for continuous color scales
## Not run: # Texas county income data library(tidycensus) tx <- get_acs(geography = "county", variables = "B19013_001", state = "TX", geometry = TRUE) # Using palette function (recommended) eq_class <- step_equal_interval(data = tx, column = "estimate", n = 5, palette = viridisLite::plasma) # Or with piping eq_class <- tx |> step_equal_interval("estimate", n = 5) # Using specific colors qt_class <- step_quantile(data = tx, column = "estimate", n = 3, colors = c("red", "yellow", "blue")) # Jenks natural breaks with default viridis jk_class <- step_jenks(data = tx, column = "estimate", n = 5) # Use in a map with formatted legend maplibre() |> add_fill_layer(source = tx, fill_color = eq_class$expression) |> add_legend( legend_title = "Median Income", values = get_legend_labels(eq_class, format = "currency"), colors = get_legend_colors(eq_class), type = "categorical" ) # Compare different methods print(eq_class, format = "currency") print(qt_class, format = "compact", prefix = "$") ## End(Not run)## Not run: # Texas county income data library(tidycensus) tx <- get_acs(geography = "county", variables = "B19013_001", state = "TX", geometry = TRUE) # Using palette function (recommended) eq_class <- step_equal_interval(data = tx, column = "estimate", n = 5, palette = viridisLite::plasma) # Or with piping eq_class <- tx |> step_equal_interval("estimate", n = 5) # Using specific colors qt_class <- step_quantile(data = tx, column = "estimate", n = 3, colors = c("red", "yellow", "blue")) # Jenks natural breaks with default viridis jk_class <- step_jenks(data = tx, column = "estimate", n = 5) # Use in a map with formatted legend maplibre() |> add_fill_layer(source = tx, fill_color = eq_class$expression) |> add_legend( legend_title = "Median Income", values = get_legend_labels(eq_class, format = "currency"), colors = get_legend_colors(eq_class), type = "categorical" ) # Compare different methods print(eq_class, format = "currency") print(qt_class, format = "compact", prefix = "$") ## End(Not run)
This function generates a step expression that can be used in your styles.
step_expr(column = NULL, property = NULL, base, values, stops, na_color = NULL)step_expr(column = NULL, property = NULL, base, values, stops, na_color = NULL)
column |
The name of the column to use for the step expression. If specified, |
property |
The name of the property to use for the step expression. If specified, |
base |
The base value to use for the step expression. |
values |
A numeric vector of values at which steps occur. |
stops |
A vector of corresponding stops (colors, sizes, etc.) for the steps. |
na_color |
The color to use for missing values. Mapbox GL JS defaults to black if this is not supplied. |
A list representing the step expression.
step_expr( column = "value", base = "#ffffff", values = c(1000, 5000, 10000), stops = c("#ff0000", "#00ff00", "#0000ff") )step_expr( column = "value", base = "#ffffff", values = c(1000, 5000, 10000), stops = c("#ff0000", "#00ff00", "#0000ff") )
Create a scrollytelling story map with Leaflet
story_leaflet( map_id, sections, root_margin = "-20% 0px -20% 0px", threshold = 0, styles = NULL, bg_color = "rgba(255,255,255,0.9)", text_color = "#34495e", font_family = NULL )story_leaflet( map_id, sections, root_margin = "-20% 0px -20% 0px", threshold = 0, styles = NULL, bg_color = "rgba(255,255,255,0.9)", text_color = "#34495e", font_family = NULL )
map_id |
The ID of your mapboxgl, maplibre, or leaflet output
defined in the server, e.g. |
sections |
A named list of story_section objects.
Names will correspond to map events defined within
the server using |
root_margin |
The margin around the viewport for triggering sections by
the intersection observer. Should be specified as a string,
e.g. |
threshold |
A number that indicates the visibility ratio for a story ' panel to be used to trigger a section; should be a number between 0 and 1. Defaults to 0, meaning that the section is triggered as soon as the first pixel is visible. |
styles |
Optional custom CSS styles. Should be specified as a
character string within |
bg_color |
Default background color for all sections |
text_color |
Default text color for all sections |
font_family |
Default font family for all sections |
Create a scrollytelling story map
story_map( map_id, sections, map_type = c("mapboxgl", "maplibre", "leaflet"), root_margin = "-20% 0px -20% 0px", threshold = 0, styles = NULL, bg_color = "rgba(255,255,255,0.9)", text_color = "#34495e", font_family = NULL )story_map( map_id, sections, map_type = c("mapboxgl", "maplibre", "leaflet"), root_margin = "-20% 0px -20% 0px", threshold = 0, styles = NULL, bg_color = "rgba(255,255,255,0.9)", text_color = "#34495e", font_family = NULL )
map_id |
The ID of your mapboxgl, maplibre, or leaflet output
defined in the server, e.g. |
sections |
A named list of story_section objects.
Names will correspond to map events defined within
the server using |
map_type |
One of |
root_margin |
The margin around the viewport for triggering sections by
the intersection observer. Should be specified as a string,
e.g. |
threshold |
A number that indicates the visibility ratio for a story ' panel to be used to trigger a section; should be a number between 0 and 1. Defaults to 0, meaning that the section is triggered as soon as the first pixel is visible. |
styles |
Optional custom CSS styles. Should be specified as a
character string within |
bg_color |
Default background color for all sections |
text_color |
Default text color for all sections |
font_family |
Default font family for all sections |
Create a scrollytelling story map with MapLibre
story_maplibre( map_id, sections, root_margin = "-20% 0px -20% 0px", threshold = 0, styles = NULL, bg_color = "rgba(255,255,255,0.9)", text_color = "#34495e", font_family = NULL )story_maplibre( map_id, sections, root_margin = "-20% 0px -20% 0px", threshold = 0, styles = NULL, bg_color = "rgba(255,255,255,0.9)", text_color = "#34495e", font_family = NULL )
map_id |
The ID of your mapboxgl, maplibre, or leaflet output
defined in the server, e.g. |
sections |
A named list of story_section objects.
Names will correspond to map events defined within
the server using |
root_margin |
The margin around the viewport for triggering sections by
the intersection observer. Should be specified as a string,
e.g. |
threshold |
A number that indicates the visibility ratio for a story ' panel to be used to trigger a section; should be a number between 0 and 1. Defaults to 0, meaning that the section is triggered as soon as the first pixel is visible. |
styles |
Optional custom CSS styles. Should be specified as a
character string within |
bg_color |
Default background color for all sections |
text_color |
Default text color for all sections |
font_family |
Default font family for all sections |
Create a story section for story maps
story_section( title, content, position = c("left", "center", "right"), width = 400, bg_color = NULL, text_color = NULL, font_family = NULL )story_section( title, content, position = c("left", "center", "right"), width = 400, bg_color = NULL, text_color = NULL, font_family = NULL )
title |
Section title |
content |
Section content - can be text, HTML, or Shiny outputs |
position |
Position of text block ("left", "center", "right") |
width |
Width of text block in pixels (default: 400) |
bg_color |
Background color (with alpha) for text block |
text_color |
Text color |
font_family |
Font family for the section |
Configure tooltip options
tooltip_options(template = NULL, theme = "auto", ...)tooltip_options(template = NULL, theme = "auto", ...)
template |
Template string or a named list with |
theme |
Visual theme: |
... |
Additional properties passed to the Mapbox/MapLibre popup, such as |
This function calculates the area of polygons in a layer or sf object. Note: This function only works with proxy objects as it returns a numeric value to R.
turf_area(proxy, layer_id = NULL, data = NULL, input_id = "turf_area_result")turf_area(proxy, layer_id = NULL, data = NULL, input_id = "turf_area_result")
proxy |
A mapboxgl_proxy or maplibre_proxy object. |
layer_id |
The ID of the layer or source containing the polygons (mutually exclusive with data). |
data |
An sf object containing polygons (mutually exclusive with layer_id). |
input_id |
Character string specifying the Shiny input ID suffix for storing the area result. Default is "turf_area_result". Result will be available as |
The proxy object for method chaining.
This module provides client-side geospatial operations using the turf.js library. All operations work with both mapboxgl and maplibre proxies. Create a buffer around geometries
turf_buffer( map, layer_id = NULL, data = NULL, coordinates = NULL, radius, units = "meters", source_id, input_id = NULL )turf_buffer( map, layer_id = NULL, data = NULL, coordinates = NULL, radius, units = "meters", source_id, input_id = NULL )
map |
A mapboxgl, maplibre, mapboxgl_proxy, or maplibre_proxy object. |
layer_id |
The ID of a layer or source to buffer (mutually exclusive with data and coordinates). |
data |
An sf object to buffer (mutually exclusive with layer_id and coordinates). |
coordinates |
A numeric vector of length 2 with lng/lat coordinates to create a point and buffer (mutually exclusive with layer_id and data). |
radius |
The buffer distance. |
units |
The units for the buffer distance. One of "meters", "kilometers", "miles", "feet", "inches", "yards", "centimeters", "millimeters", "degrees", "radians". |
source_id |
The ID for the new source containing the buffered results. Required. |
input_id |
Optional. Character string specifying the Shiny input ID suffix for storing results. If NULL (default), no input is registered. For proxy operations, the result will be available as |
This function creates a buffer around geometries at a specified distance. The operation is performed client-side using turf.js. The result is added as a source to the map, which can then be styled using add_fill_layer(), add_line_layer(), etc.
The map or proxy object for method chaining.
## Not run: # Buffer existing layer map |> turf_buffer(layer_id = "points", radius = 1000, units = "meters", source_id = "point_buffers") |> add_fill_layer(id = "buffers", source = "point_buffers", fill_color = "blue") # Buffer sf object map |> turf_buffer(data = sf_points, radius = 0.5, units = "miles", source_id = "buffers") |> add_fill_layer(id = "buffer_layer", source = "buffers") # Buffer coordinates (great for hover events) maplibre_proxy("map") |> turf_buffer(coordinates = c(-122.4, 37.7), radius = 500, units = "meters", source_id = "hover_buffer") ## End(Not run)## Not run: # Buffer existing layer map |> turf_buffer(layer_id = "points", radius = 1000, units = "meters", source_id = "point_buffers") |> add_fill_layer(id = "buffers", source = "point_buffers", fill_color = "blue") # Buffer sf object map |> turf_buffer(data = sf_points, radius = 0.5, units = "miles", source_id = "buffers") |> add_fill_layer(id = "buffer_layer", source = "buffers") # Buffer coordinates (great for hover events) maplibre_proxy("map") |> turf_buffer(coordinates = c(-122.4, 37.7), radius = 500, units = "meters", source_id = "hover_buffer") ## End(Not run)
This function calculates the center of mass (geometric centroid) for each feature. Uses turf.centerOfMass which provides more accurate centroids than turf.centroid, matching the behavior of sf::st_centroid() and PostGIS ST_Centroid. The result is added as a source to the map, which can then be styled using add_circle_layer(), etc.
turf_center_of_mass( map, layer_id = NULL, data = NULL, coordinates = NULL, source_id, input_id = NULL )turf_center_of_mass( map, layer_id = NULL, data = NULL, coordinates = NULL, source_id, input_id = NULL )
map |
A mapboxgl, maplibre, mapboxgl_proxy, or maplibre_proxy object. |
layer_id |
The ID of a layer or source (mutually exclusive with data and coordinates). |
data |
An sf object (mutually exclusive with layer_id and coordinates). |
coordinates |
A list of coordinate pairs list(c(lng,lat), c(lng,lat), ...) for multiple points (mutually exclusive with layer_id and data). |
source_id |
The ID for the new source containing the center of mass points. Required. |
input_id |
Optional. Character string specifying the Shiny input ID suffix for storing results. If NULL (default), no input is registered. For proxy operations, the result will be available as |
The map or proxy object for method chaining.
This function calculates the centroid of geometries in a layer or sf object. The result is added as a source to the map, which can then be styled using add_circle_layer(), etc.
turf_centroid( map, layer_id = NULL, data = NULL, coordinates = NULL, source_id, input_id = NULL )turf_centroid( map, layer_id = NULL, data = NULL, coordinates = NULL, source_id, input_id = NULL )
map |
A mapboxgl, maplibre, mapboxgl_proxy, or maplibre_proxy object. |
layer_id |
The ID of a layer or source containing geometries (mutually exclusive with data and coordinates). |
data |
An sf object containing geometries (mutually exclusive with layer_id and coordinates). |
coordinates |
A list of coordinate pairs list(c(lng,lat), c(lng,lat), ...) for multiple points (mutually exclusive with layer_id and data). |
source_id |
The ID for the new source containing the centroid. Required. |
input_id |
Optional. Character string specifying the Shiny input ID suffix for storing results. If NULL (default), no input is registered. For proxy operations, the result will be available as |
The map or proxy object for method chaining.
This function creates a concave hull around a set of points. The result is added as a source to the map, which can then be styled using add_fill_layer(), etc.
turf_concave_hull( map, layer_id = NULL, data = NULL, coordinates = NULL, max_edge = NULL, units = "kilometers", source_id, input_id = NULL )turf_concave_hull( map, layer_id = NULL, data = NULL, coordinates = NULL, max_edge = NULL, units = "kilometers", source_id, input_id = NULL )
map |
A mapboxgl, maplibre, mapboxgl_proxy, or maplibre_proxy object. |
layer_id |
The ID of a layer or source containing points (mutually exclusive with data and coordinates). |
data |
An sf object containing points (mutually exclusive with layer_id and coordinates). |
coordinates |
A list of coordinate pairs list(c(lng,lat), c(lng,lat), ...) for multiple points (mutually exclusive with layer_id and data). |
max_edge |
The maximum edge length for the concave hull. If NULL (default), an optimal value is calculated automatically. |
units |
The units for max_edge. One of "meters", "kilometers", "miles", etc. |
source_id |
The ID for the new source containing the concave hull. Required. |
input_id |
Optional. Character string specifying the Shiny input ID suffix for storing results. If NULL (default), no input is registered. For proxy operations, the result will be available as |
If max_edge is too small and no concave hull can be computed, the function will automatically calculate an optimal max_edge value based on point distances. If that fails, it falls back to a convex hull to ensure a result is always returned.
The map or proxy object for method chaining.
This function creates a convex hull around a set of points. The result is added as a source to the map, which can then be styled using add_fill_layer(), etc.
turf_convex_hull( map, layer_id = NULL, data = NULL, coordinates = NULL, source_id, input_id = NULL )turf_convex_hull( map, layer_id = NULL, data = NULL, coordinates = NULL, source_id, input_id = NULL )
map |
A mapboxgl, maplibre, mapboxgl_proxy, or maplibre_proxy object. |
layer_id |
The ID of a layer or source containing points (mutually exclusive with data and coordinates). |
data |
An sf object containing points (mutually exclusive with layer_id and coordinates). |
coordinates |
A list of coordinate pairs list(c(lng,lat), c(lng,lat), ...) for multiple points (mutually exclusive with layer_id and data). |
source_id |
The ID for the new source containing the convex hull. Required. |
input_id |
Optional. Character string specifying the Shiny input ID suffix for storing results. If NULL (default), no input is registered. For proxy operations, the result will be available as |
The map or proxy object for method chaining.
This function subtracts the second geometry from the first. The result is added as a source to the map, which can then be styled using add_fill_layer(), etc.
turf_difference( map, layer_id = NULL, layer_id_2 = NULL, data = NULL, data_2 = NULL, source_id, input_id = NULL )turf_difference( map, layer_id = NULL, layer_id_2 = NULL, data = NULL, data_2 = NULL, source_id, input_id = NULL )
map |
A mapboxgl, maplibre, mapboxgl_proxy, or maplibre_proxy object. |
layer_id |
The ID of the first layer or source (geometry to subtract from, mutually exclusive with data). |
layer_id_2 |
The ID of the second layer or source (geometry to subtract, mutually exclusive with data_2). |
data |
An sf object for the first geometry (mutually exclusive with layer_id). |
data_2 |
An sf object for the second geometry (mutually exclusive with layer_id_2). |
source_id |
The ID for the new source containing the difference result. Required. |
input_id |
Optional. Character string specifying the Shiny input ID suffix for storing results. If NULL (default), no input is registered. For proxy operations, the result will be available as |
The map or proxy object for method chaining.
This function calculates the distance between the first features of two layers or coordinates. Note: This function only works with proxy objects as it returns a numeric value to R.
turf_distance( proxy, layer_id = NULL, layer_id_2 = NULL, data = NULL, coordinates = NULL, coordinates_2 = NULL, units = "kilometers", input_id = "turf_distance_result" )turf_distance( proxy, layer_id = NULL, layer_id_2 = NULL, data = NULL, coordinates = NULL, coordinates_2 = NULL, units = "kilometers", input_id = "turf_distance_result" )
proxy |
A mapboxgl_proxy or maplibre_proxy object. |
layer_id |
The ID of the first layer or source (mutually exclusive with data and coordinates). |
layer_id_2 |
The ID of the second layer or source (required if layer_id is used). |
data |
An sf object for the first geometry (mutually exclusive with layer_id and coordinates). |
coordinates |
A numeric vector of length 2 with lng/lat coordinates for the first point (mutually exclusive with layer_id and data). |
coordinates_2 |
A numeric vector of length 2 with lng/lat coordinates for the second point (required if coordinates is used). |
units |
The units for the distance calculation. One of "meters", "kilometers", "miles", etc. |
input_id |
Character string specifying the Shiny input ID suffix for storing the distance result. Default is "turf_distance_result". Result will be available as |
The proxy object for method chaining.
This function filters features from the first layer based on their spatial relationship with features in the second layer using various spatial predicates.
turf_filter( map, layer_id = NULL, filter_layer_id = NULL, data = NULL, filter_data = NULL, predicate = c("intersects", "within", "contains", "crosses", "disjoint"), source_id, input_id = NULL )turf_filter( map, layer_id = NULL, filter_layer_id = NULL, data = NULL, filter_data = NULL, predicate = c("intersects", "within", "contains", "crosses", "disjoint"), source_id, input_id = NULL )
map |
A mapboxgl, maplibre, mapboxgl_proxy, or maplibre_proxy object. |
layer_id |
The ID of the layer or source to filter (mutually exclusive with data). |
filter_layer_id |
The ID of the layer or source to filter against (mutually exclusive with filter_data). |
data |
An sf object containing features to filter (mutually exclusive with layer_id). |
filter_data |
An sf object containing the filter geometry (mutually exclusive with filter_layer_id). |
predicate |
The spatial relationship to test. One of: "intersects", "within", "contains", "crosses", "disjoint". |
source_id |
The ID for the new source containing the filtered results. Required. |
input_id |
Optional. Character string specifying the Shiny input ID suffix for storing results. If NULL (default), no input is registered. For proxy operations, the result will be available as |
The map or proxy object for method chaining.
This function finds the intersection between geometries in two layers or sf objects. The result is added as a source to the map, which can then be styled using add_fill_layer(), etc.
turf_intersect( map, layer_id = NULL, layer_id_2 = NULL, data = NULL, data_2 = NULL, source_id, input_id = NULL )turf_intersect( map, layer_id = NULL, layer_id_2 = NULL, data = NULL, data_2 = NULL, source_id, input_id = NULL )
map |
A mapboxgl, maplibre, mapboxgl_proxy, or maplibre_proxy object. |
layer_id |
The ID of the first layer or source (mutually exclusive with data). |
layer_id_2 |
The ID of the second layer or source (mutually exclusive with data_2). |
data |
An sf object for the first geometry (mutually exclusive with layer_id). |
data_2 |
An sf object for the second geometry (mutually exclusive with layer_id_2). |
source_id |
The ID for the new source containing the intersection result. Required. |
input_id |
Optional. Character string specifying the Shiny input ID suffix for storing results. If NULL (default), no input is registered. For proxy operations, the result will be available as |
The map or proxy object for method chaining.
This function unions all polygons in a layer into a single geometry. The result is added as a source to the map, which can then be styled using add_fill_layer(), etc.
turf_union(map, layer_id = NULL, data = NULL, source_id, input_id = NULL)turf_union(map, layer_id = NULL, data = NULL, source_id, input_id = NULL)
map |
A mapboxgl, maplibre, mapboxgl_proxy, or maplibre_proxy object. |
layer_id |
The ID of a layer or source to union (mutually exclusive with data). |
data |
An sf object to union (mutually exclusive with layer_id). |
source_id |
The ID for the new source containing the union result. Required. |
input_id |
Optional. Character string specifying the Shiny input ID suffix for storing results. If NULL (default), no input is registered. For proxy operations, the result will be available as |
The map or proxy object for method chaining.
This function creates a Voronoi diagram from a set of points. The result is added as a source to the map, which can then be styled using add_fill_layer(), etc.
turf_voronoi( map, layer_id = NULL, data = NULL, coordinates = NULL, bbox = NULL, property = NULL, source_id, input_id = NULL )turf_voronoi( map, layer_id = NULL, data = NULL, coordinates = NULL, bbox = NULL, property = NULL, source_id, input_id = NULL )
map |
A mapboxgl, maplibre, mapboxgl_proxy, or maplibre_proxy object. |
layer_id |
The ID of a layer or source containing points (mutually exclusive with data and coordinates). |
data |
An sf object containing points (mutually exclusive with layer_id and coordinates). |
coordinates |
A list of coordinate pairs list(c(lng,lat), c(lng,lat), ...) for multiple points (mutually exclusive with layer_id and data). |
bbox |
Optional. Can be: (1) A numeric vector of length 4, in format ‘c(xmin, ymin, xmax, ymax)’, (2) An sf object to extract bbox from, or (3) A layer_id string to extract bbox from and clip results to. |
property |
Optional. Character string specifying a column name from the input points to transfer to the Voronoi polygons using spatial collection. |
source_id |
The ID for the new source containing the Voronoi diagram. Required. |
input_id |
Optional. Character string specifying the Shiny input ID suffix for storing results. If NULL (default), no input is registered. For proxy operations, the result will be available as |
The map or proxy object for method chaining.