### Initialize Maplibre GL JS Map with Default Tiles Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/getting-started.html Initializes a Maplibre GL JS map using the mapgl package with CARTO's Voyager tiles. This requires the mapgl library and does not need an API key. ```R library(mapgl) maplibre() ``` -------------------------------- ### Visualize NC Data with maplibre_view Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/getting-started.html Demonstrates visualizing the North Carolina dataset using the `maplibre_view` function, specifying the 'AREA' column for styling. This function processes sf objects and automatically generates a map with a color scale based on the specified column. ```R library(sf) ## Linking to GEOS 3.13.0, GDAL 3.8.5, PROJ 9.5.1; sf_use_s2() is TRUE # Quick view of the North Carolina dataset nc <- st_read(system.file("shape/nc.shp", package="sf")) ## Reading layer `nc' from data source ## `/Library/Frameworks/R.framework/Versions/4.5-arm64/Resources/library/sf/shape/nc.shp' ## using driver `ESRI Shapefile' ## Simple feature collection with 100 features and 14 fields ## Geometry type: MULTIPOLYGON ## Dimension: XY ## Bounding box: xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965 ## Geodetic CRS: NAD27 maplibre_view(nc, column = "AREA") ``` -------------------------------- ### Initialize Maplibre GL JS Map with MapTiler Style and Controls Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/getting-started.html Initializes a Maplibre GL JS map with a specified MapTiler style ('bright') and adds fullscreen and navigation controls. This requires setting the MAPTILER_API_KEY environment variable. ```R maplibre( style = maptiler_style("bright"), center = c(-43.23412, -22.91370), zoom = 14 ) |> add_fullscreen_control(position = "top-left") |> add_navigation_control() ``` -------------------------------- ### Animate map view with fly_to in mapgl Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/getting-started.html This R code shows how to create a 'fly to' animation for a mapgl map. It uses the mapboxgl() function to set an initial view and then pipes the result to the fly_to() function to smoothly transition the map to a new center, zoom level, pitch, and bearing. ```r mapboxgl( center = c(-97.6, 25.4) ) |> fly_to( center = c(-96.810481, 32.790869), zoom = 18.4, pitch = 75, bearing = 136.8 ) ``` -------------------------------- ### Initialize Mapbox GL JS map with default settings Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/getting-started.html This R code initializes an interactive map using the mapboxgl() function from the mapgl package. It defaults to Mapbox's Standard style and a globe projection. Ensure you have a Mapbox access token set as an environment variable (MAPBOX_PUBLIC_TOKEN) for the map to render correctly. ```r library(mapgl) mapboxgl() ``` -------------------------------- ### Customize Mapbox GL JS map style and projection Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/getting-started.html This R code snippet demonstrates how to customize the appearance of a mapgl map by specifying a different Mapbox style (e.g., 'satellite') and projection (e.g., 'winkelTripel'). The mapbox_style() function helps in accessing various Mapbox styles. ```r mapboxgl( style = mapbox_style("satellite"), projection = "winkelTripel") ``` -------------------------------- ### Build and Install R Package Source: https://github.com/walkerke/mapgl/blob/main/docs/CLAUDE.html Common commands for building and installing the mapgl R package locally using devtools. These commands are essential for development and testing. ```R devtools::install() devtools::check() devtools::document() devtools::test() devtools::build() ``` -------------------------------- ### Install mapgl from GitHub Source: https://github.com/walkerke/mapgl/blob/main/docs/index.html Installs the development version of the mapgl package directly from its GitHub repository. This is useful for accessing the latest features or bug fixes. ```r remotes::install_github("walkerke/mapgl") ``` -------------------------------- ### Manage R Package Vignettes and Documentation Source: https://github.com/walkerke/mapgl/blob/main/docs/CLAUDE.html Commands to build vignettes and the pkgdown documentation site for the mapgl R package. These are crucial for generating user-facing documentation and examples. ```R devtools::build_vignettes() knitr::knit("vignettes/getting-started.Rmd") pkgdown::build_site() ``` -------------------------------- ### Create Map Source and Layer Source: https://github.com/walkerke/mapgl/blob/main/docs/CLAUDE.html Example of creating both a data source and a layer simultaneously using the add_circle_layer function in mapgl. ```R add_circle_layer(map, id = "circles", source = "data", data = sf_object) ``` -------------------------------- ### Install mapgl from CRAN Source: https://github.com/walkerke/mapgl/blob/main/docs/index.html Installs the mapgl package from the Comprehensive R Archive Network (CRAN). This is the standard way to install stable releases of R packages. ```r install.packages("mapgl") ``` -------------------------------- ### Story Map with Data Visualization (Isochrone) Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/story-maps.html This example integrates data visualization by calculating and displaying an isochrone using `mb_isochrone()` and customizing the story map's appearance with Google Fonts. It requires `shiny`, `mapgl`, and `mapboxapi` libraries. ```r library(shiny) library(mapgl) library(mapboxapi) property <- c(-97.71326, 30.402550) isochrone <- mb_isochrone(property, profile = "driving", time = 20) ui <- fluidPage( tags$link(href = "https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap", rel="stylesheet"), story_map( map_id = "map", font_family = "Poppins", sections = list( "intro" = story_section( title = "MULTIFAMILY INVESTMENT OPPORTUNITY", content = list( p("New Class A Apartments in Austin, Texas"), img(src = "apartment.png", width = "300px") ), position = "center" ), "marker" = story_section( title = "PROPERTY LOCATION", content = list( p("The property will be located in the thriving Domain district of north Austin, home to some of the city's best shopping, dining, and entertainment.") ) ), "isochrone" = story_section( title = "AUSTIN AT YOUR FINGERTIPS", content = list( p("The property is within a 20-minute drive of downtown Austin, the University of Texas, and the city's major employers.") ) ) ) ) ) server <- function(input, output, session) { output$map <- renderMapboxgl({ mapboxgl(scrollZoom = FALSE, ``` -------------------------------- ### Story Map with Multiple Section Transitions Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/story-maps.html An extended example showing how to define `on_section()` events for multiple sections, including returning to a default view for the 'intro' section and zooming to a specific location for the 'location' section. Requires `shiny` and `mapgl`. ```r library(shiny) library(mapgl) ui <- fluidPage( story_map( map_id = "map", sections = list( "intro" = story_section( "Introduction", "This is a story map." ), "location" = story_section( "Location", "Check out this interesting location." ) ) ) ) server <- function(input, output, session) { output$map <- renderMapboxgl({ mapboxgl(scrollZoom = FALSE) }) on_section("map", "intro", { mapboxgl_proxy("map") |> fly_to(center = c(0, 0), zoom = 0, pitch = 0, bearing = 0) }) on_section("map", "location", { mapboxgl_proxy("map") |> fly_to(center = c(12.49257, 41.890233), zoom = 17.5, pitch = 49, bearing = 12.8) }) } shinyApp(ui, server) ``` -------------------------------- ### Shiny App with Maplibre Compare Widget Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/compare.html A complete Shiny app example demonstrating the use of `maplibreCompareOutput` and `renderMaplibreCompare`. It includes updating map styles via proxies and setting custom swiper colors. ```r library(shiny) library(mapgl) 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 ) }) } ``` -------------------------------- ### Map Comparison Examples Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/compare.html Illustrates various ways to use the `compare` function for creating map comparisons, including default swipe mode, synchronized side-by-side mode, and custom swiper colors. ```r 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") # Custom swiper color compare(m1, m2, swiper_color = "#FF0000") # Red swiper ``` -------------------------------- ### Mapbox GL Expression Example Source: https://github.com/walkerke/mapgl/blob/main/docs/CLAUDE.html Illustrates the use of Mapbox GL expressions for interpolating values based on colors. ```R interpolate( column = "value", values = c(0, 100), colors = c("blue", "red") ) ``` -------------------------------- ### Shiny App with Clicked Feature Output Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/shiny.html This example extends a basic Shiny app to display information about features clicked on the map. It uses input$map_feature_click to capture click events and renderPrint to display the clicked feature's properties. ```r ui <- page_sidebar( title = "mapgl with Shiny", sidebar = sidebar( verbatimTextOutput("clicked_feature") ), card( full_screen = TRUE, maplibreOutput("map") ) ) server <- function(input, output, session) { output$map <- renderMaplibre({ maplibre(style = carto_style("positron")) |> fit_bounds(nc, animate = FALSE) |> add_fill_layer(id = "nc_data", source = nc, fill_color = "blue", fill_opacity = 0.5) }) output$clicked_feature <- renderPrint({ req(input$map_feature_click) input$map_feature_click }) } shinyApp(ui, server) ``` -------------------------------- ### Utility Functions for Map Properties and Expressions Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/index.html Utility functions for creating specific map properties and expressions, such as getting column data, concatenating strings, formatting numbers, and preparing cluster options. ```R get_column() concat() number_format() cluster_options() get_style() ``` -------------------------------- ### Add Fill-Extrusion Layer for 3D Buildings with Vector Tiles Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/layers-overview.html This example shows how to create a fill-extrusion layer to render 3D buildings using mapgl. It utilizes vector tiles from MapTiler and customizes the extrusion height and color based on building data properties and zoom levels. The map includes pitch and bearing for a 3D perspective. ```r 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') ) ) ``` -------------------------------- ### Example: Applying step_equal_interval and adding to mapgl Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/step_classification.html Demonstrates how to use the step_equal_interval function with the viridisLite::plasma palette and then apply the resulting expression to a mapgl fill layer. It also shows how to add a formatted legend using get_legend_labels and get_legend_colors. ```R library(tidycensus) library(maplibre) 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) # 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 = "$") ``` -------------------------------- ### Integrating Shiny Inputs and Outputs in mapgl Story Maps Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/story-maps.html Illustrates how to embed Shiny inputs (selectInput) and outputs (plotOutput, uiOutput) within mapgl story sections to create interactive elements. This example dynamically displays county information and histograms based on user selection. ```r library(shiny) library(mapgl) library(tidycensus) library(tidyverse) library(sf) fl_age <- get_acs( geography = "tract", variables = "B01001_001", state = "FL", year = 2023, geometry = TRUE ) |> separate_wider_delim(NAME, delim = "; ", names = c("tract", "county", "state")) %>% st_sf() ui <- fluidPage( story_maplibre( map_id = "map", sections = list( "intro" = story_section( "Median Age in Florida", content = list( selectInput( "county", "Select a county", choices = sort(unique(fl_age$county)) ), p("Scroll down to view the median age distribution in the selected county.") ) ), "county" = story_section( title = NULL, content = list( uiOutput("county_text"), plotOutput("county_plot") ) ) ) ) ) server <- function(input, output, session) { sel_county <- reactive({ # Server logic for selected county }) } ``` -------------------------------- ### Initialize Mapbox GL Map with Globe Projection Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/mapboxgl.html Initializes a Mapbox GL map using the mapgl R package with a 'globe' projection. This is a common starting point for creating interactive maps. ```r if (FALSE) { # \dontrun{ mapboxgl(projection = "globe") } # } ``` -------------------------------- ### Example: Visualize 3D Buildings with mapgl (R) Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/add_fill_extrusion_layer.html Demonstrates how to add a fill extrusion layer to visualize 3D buildings using mapgl. It sets up a Mapbox GL map, adds a vector tile source, and then applies the `add_fill_extrusion_layer` function. The extrusion height and color are dynamically set based on feature properties and zoom levels, providing a 3D effect. ```r 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") ) ) ``` -------------------------------- ### Example: Classifying and labeling Texas county income data Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/classification_helpers.html Demonstrates using mapgl functions to classify county income data from the tidycensus package and then extract legend labels, colors, and breaks. ```r if (FALSE) { # \dontrun{ # 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) } # } ``` -------------------------------- ### Example: Adding Layers Control with Customization (R) Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/add_layers_control.html Demonstrates adding a layers control to a map with specified background and active colors. It also shows how to use custom labels for layers and group multiple layers under a single control item. ```r 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" ) ) ``` -------------------------------- ### Creating Maps API Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/index.html Functions to initialize Mapbox GL and MapLibre GL maps. ```APIDOC ## GET mapboxgl() ### Description Initialize a Mapbox GL Map ### Method GET ### Endpoint /mapboxgl ## GET maplibre() ### Description Initialize a Maplibre GL Map ### Method GET ### Endpoint /maplibre ## GET mapboxgl_view() ### Description Quick visualization of geometries with Mapbox GL ### Method GET ### Endpoint /mapboxgl_view ## GET maplibre_view() ### Description Quick visualization of geometries with MapLibre GL ### Method GET ### Endpoint /maplibre_view ``` -------------------------------- ### Basic Story Map with Section Transition Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/story-maps.html Demonstrates setting up a basic story map with two sections and using `on_section()` to trigger a map fly-to animation when the 'location' section is active. Requires `shiny` and `mapgl` libraries. ```r library(shiny) library(mapgl) ui <- fluidPage( story_map( map_id = "map", sections = list( "intro" = story_section( "Introduction", "This is a story map." ), "location" = story_section( "Location", "Check out this interesting location." ) ) ) ) server <- function(input, output, session) { output$map <- renderMapboxgl({ mapboxgl(scrollZoom = FALSE) }) on_section("map", "location", { mapboxgl_proxy("map") |> fly_to(center = c(12.49257, 41.890233), zoom = 17.5, pitch = 49, bearing = 12.8) }) } shinyApp(ui, server) ``` -------------------------------- ### Get CARTO Style URL in R Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/carto_style.html The `carto_style` function takes a style name as input and returns the corresponding CARTO style URL. This is useful for applying pre-defined visual styles to maps generated with mapgl. ```R carto_style(style_name) ``` -------------------------------- ### Quick Visualization with Mapbox GL Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/index.html Provides a quick way to visualize geometries using Mapbox GL. This is useful for rapid prototyping and displaying simple spatial data. ```R mapboxgl_view() ``` -------------------------------- ### Get Mapbox Style URL in R Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/mapbox_style.html Retrieves the Mapbox style URL for a given style name. The function takes a single argument, 'style_name', which is a string representing the desired Mapbox style (e.g., 'standard', 'streets'). It returns the corresponding style URL. ```r mapbox_style(style_name) ``` -------------------------------- ### Get Drawn Features in Shiny App - R Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/get_drawn_features.html Demonstrates how to use `get_drawn_features` within a Shiny application to capture and display features drawn by the user on a map. It requires the `shiny` and `mapgl` libraries and utilizes `mapboxglOutput`, `renderMapboxgl`, `add_draw_control`, `mapboxgl_proxy`, `actionButton`, and `verbatimTextOutput`. ```R 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) ``` -------------------------------- ### Add Circle Layer Example in R Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/add_circle_layer.html Demonstrates how to add a circle layer to a Mapbox GL map using the `add_circle_layer` function. It includes generating random points, assigning categories, and setting up map layers. This example requires the `mapgl`, `sf`, and `dplyr` R packages. ```R 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, size = n(), replace = TRUE)) # Create a base map (assuming a map object 'map' is already created) # Example: map <- mapbox(style = 'dark') # Add the circle layer to the map # map <- add_circle_layer( # map, # id = "random-circles", # source = random_points, # circle_radius = 10, # circle_color = "#4899d0", # circle_opacity = 0.8 # ) # Note: The actual map creation and display code is commented out as it requires a `map` object to be initialized. ``` -------------------------------- ### Get MapTiler Style URL with maptiler_style function (R) Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/maptiler_style.html This R code snippet demonstrates how to use the `maptiler_style` function to obtain a MapTiler style URL. The function requires a style name and optionally accepts a color variant and an API key. It returns the corresponding style URL. ```R maptiler_style(style_name, variant = NULL, api_key = NULL) ``` -------------------------------- ### Initialize Mapbox GL Map Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/index.html Initializes a Mapbox GL map. This function is used to create a base map object for further customization. It requires a Mapbox GL API key. ```R mapboxgl() ``` -------------------------------- ### Get queried features from mapgl layer Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/get_queried_features.html Retrieves features queried from a mapgl layer as an sf object. Requires a map object and optionally uses query_rendered_features to initiate the query. Returns an sf object, or an empty sf object if no features are found. Only visible features at query time are included. ```r if (FALSE) { # \dontrun{ # 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)) }) } # } ``` -------------------------------- ### Shiny Integration for Mapbox GL and Maplibre GL Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/index.html Functions for integrating mapgl with Shiny applications, including creating output elements, rendering maps, creating proxy objects, and enabling hover events. ```R mapboxglOutput() maplibreOutput() renderMapboxgl() renderMaplibre() mapboxgl_proxy() maplibre_proxy() mapboxglCompareOutput() maplibreCompareOutput() renderMapboxglCompare() renderMaplibreCompare() mapboxgl_compare_proxy() maplibre_compare_proxy() enable_shiny_hover() ``` -------------------------------- ### Classification Helper Functions Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/index.html Helper functions for extracting information from classification and continuous scale objects, including getting legend labels, colors, and breaks. ```R get_legend_labels() get_legend_colors() get_breaks() print(__) print(__) ``` -------------------------------- ### Basic Shiny App Structure for mapgl Story Maps Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/story-maps.html This R code sets up a basic Shiny application UI and server to create a story map. It utilizes `fluidPage` and `story_map` for the UI, and `renderMapboxgl` with `mapboxgl` for the map display. The map is initialized with `scrollZoom = FALSE` to avoid conflicts with story scrolling. ```r library(shiny) library(mapgl) ui <- fluidPage( story_map( map_id = "map", sections = list( "intro" = story_section( "Introduction", "This is a story map." ), "location" = story_section( "Location", "Check out this interesting location." ) ) ) ) server <- function(input, output, session) { output$map <- renderMapboxgl({ mapboxgl(scrollZoom = FALSE) }) } shinyApp(ui, server) ``` -------------------------------- ### Quick Visualization with MapLibre GL Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/index.html Enables quick visualization of geometries using MapLibre GL. This function is suitable for users who prefer or require an open-source mapping solution. ```R maplibre_view() ``` -------------------------------- ### Get MapTiler Style URL Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/index.html Retrieves a MapTiler Style URL, providing access to various map styles offered by MapTiler. This function is an alternative for map styling. ```R maptiler_style() ``` -------------------------------- ### Add Heatmap Layer Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/layers-overview.html This section details how to add a heatmap layer to visualize point density. It includes parameters for source data, heatmap weight, intensity, color, and opacity. ```APIDOC ## POST /api/heatmap-layer ### Description Adds a heatmap layer to visualize the density of points. ### Method POST ### Endpoint /api/heatmap-layer ### Parameters #### Request Body - **id** (string) - Required - A unique identifier for the layer. - **source** (object) - Required - Defines the data source for the layer. - **type** (string) - Required - The type of the source (e.g., "geojson"). - **data** (string or object) - Required - The data for the source (e.g., a URL to a GeoJSON file or a GeoJSON object). - **heatmap_weight** (object) - Optional - Defines how the weight of each point is calculated. - **column** (string) - Required - The property to use for calculating weight. - **values** (array) - Required - An array of values to interpolate from. - **stops** (array) - Required - An array of stop values for interpolation. - **heatmap_intensity** (object) - Optional - Controls the intensity of the heatmap based on zoom level. - **property** (string) - Required - The property to use for intensity calculation (usually "zoom"). - **values** (array) - Required - An array of zoom values. - **stops** (array) - Required - An array of intensity stops. - **heatmap_color** (object) - Optional - Defines the color gradient for the heatmap. - **property** (string) - Required - The property to use for color calculation (usually "heatmap-density"). - **values** (array) - Required - An array of density values. - **stops** (array) - Required - An array of color stops. - **heatmap_opacity** (number) - Optional - The opacity of the heatmap layer. ### Request Example ```json { "id": "earthquakes-heat", "source": { "type": "geojson", "data": "https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson" }, "heatmap_weight": { "column": "mag", "values": [0, 6], "stops": [0, 1] }, "heatmap_intensity": { "property": "zoom", "values": [0, 9], "stops": [1, 3] }, "heatmap_color": { "property": "heatmap-density", "values": [0, 0.2, 0.4, 0.6, 0.8, 1], "stops": [ '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 } ``` ### Response #### Success Response (200) Returns a confirmation message or status indicating the layer was added. #### Response Example ```json { "message": "Heatmap layer added successfully" } ``` ``` -------------------------------- ### compare() - Create Compare Widget Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/index.html Creates a Compare widget, likely for side-by-side visualization of different map layers or versions. This is useful for comparing datasets or map states. It requires map instances or layer configurations. ```javascript function compare(map1, map2, options) { // Implementation to create and integrate a compare widget // Example: new mapgl.Compare(map1, map2, options); return null; // Placeholder } ``` -------------------------------- ### Get Column/Property Expression - R Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/get_column.html Retrieves an expression for a specified column or property to be used in mapgl. The function takes the column name as input and returns a list representing the expression. ```R get_column(column) ``` -------------------------------- ### Get Mapbox Style URL Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/index.html Retrieves a valid Mapbox Style URL, which defines the visual appearance of a Mapbox GL map. This function simplifies map styling configuration. ```R mapbox_style() ``` -------------------------------- ### Load and Test R Functions Source: https://github.com/walkerke/mapgl/blob/main/docs/CLAUDE.html Loads the development version of the mapgl package and demonstrates testing individual functions, including adding a circle layer. ```R devtools::load_all() library(mapgl) map <- maplibre() |> add_circle_layer(data = sf_object, ...) ``` -------------------------------- ### Create map expressions (interpolate, match, step) Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/index.html Functions to create various types of expressions for map styling and data visualization, such as interpolation, matching, and stepping. ```R interpolate() match_expr() step_expr() ``` -------------------------------- ### Get break points from mapgl objects Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/classification_helpers.html Extracts the numerical break points used in mapgl classification objects. ```r get_breaks(scale) ``` -------------------------------- ### Load R Package for Development Source: https://github.com/walkerke/mapgl/blob/main/docs/CLAUDE.html Loads the mapgl package using devtools::load_all(), which is useful for testing R changes during development. ```R devtools::load_all() ``` -------------------------------- ### Get legend colors from mapgl objects Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/classification_helpers.html Retrieves a character vector of colors used in the legend for mapgl classification or continuous scale objects. ```r get_legend_colors(scale) ``` -------------------------------- ### Add Symbol Layer with Icon and Tooltip (R) Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/layers-overview.html Demonstrates adding a symbol layer to a Mapbox map using R. It customizes the icon based on a 'category' column and sets a tooltip for the same. Requires the 'mapbox' package and a valid Mapbox style. ```R mapboxgl(style = mapbox_style("light"), bounds = random_points) |> add_symbol_layer( id = "points-of-interest", source = random_points, icon_image = get_column("category"), icon_allow_overlap = TRUE, tooltip = "category" ) ``` -------------------------------- ### GeoJSON LineString Feature Example Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/layers-overview.html This snippet represents a GeoJSON Feature object with a LineString geometry. It includes properties such as LINEARID, FULLNAME, RTTYP, and MTFCC, defining a road segment with its geographical path. ```json { "type": "Feature", "properties": { "LINEARID": "11015482446706", "FULLNAME": null, "RTTYP": null, "MTFCC": "S1400" }, "geometry": { "type": "LineString", "coordinates": [ [ -103.813052, 31.899217 ], [ -103.81034, 31.899285 ] ] } } ``` -------------------------------- ### Add Fill-Extrusion Layer Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/layers-overview.html This section explains how to add a fill-extrusion layer for 3D building visualization. It covers parameters for source data, source layers, fill extrusion color, and height. ```APIDOC ## POST /api/fill-extrusion-layer ### Description Adds a fill-extrusion layer to create 3D building visualizations. ### Method POST ### Endpoint /api/fill-extrusion-layer ### Parameters #### Request Body - **id** (string) - Required - A unique identifier for the layer. - **source** (string) - Required - The ID of the vector tile source. - **source_layer** (string) - Required - The specific layer within the vector tile source. - **fill_extrusion_color** (object) - Optional - Defines the color of the extruded polygons. - **column** (string) - Required - The property to use for color interpolation. - **values** (array) - Required - An array of height values for color stops. - **stops** (array) - Required - An array of color values corresponding to the height values. - **fill_extrusion_height** (object) - Optional - Defines the extrusion height of the polygons. - **interpolate** (array) - Required - Specifies interpolation method and properties. - **type** (string) - Required - Interpolation type (e.g., "linear"). - **property** (string) - Required - Property to interpolate on (e.g., "zoom" or a data property). - **values** (array) - Required - Array of zoom levels or data values. - **stops** (array) - Required - Array of corresponding extrusion heights. ### Request Example ```json { "id": "3d-buildings", "source": "openmaptiles", "source_layer": "building", "fill_extrusion_color": { "column": "render_height", "values": [0, 200, 400], "stops": ['lightgray', 'royalblue', 'lightblue'] }, "fill_extrusion_height": { "interpolate": [ "linear", ["zoom"], 15, 0, 16, ["get", "render_height"] ] } } ``` ### Response #### Success Response (200) Returns a confirmation message or status indicating the layer was added. #### Response Example ```json { "message": "Fill-extrusion layer added successfully" } ``` ``` -------------------------------- ### Create and Style Circle Layers with Categorical Data in R Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/layers-overview.html Demonstrates creating a map with a circle layer representing points of interest. Points are styled based on their 'category' property using a categorical color scale. It also includes adding a legend that visually corresponds to the category colors and shapes. Tooltips and hover effects are configured for interactivity. ```R 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("dark"), bounds = random_points) %>% 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"), patch_shape = "circle" ) ``` -------------------------------- ### GeoJSON Feature with Null Properties Example Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/layers-overview.html This code demonstrates a GeoJSON Feature where some properties, like FULLNAME and RTTYP, are null. This is common when certain data fields are not available or applicable for a given feature. The geometry is a LineString. ```json { "type": "Feature", "properties": { "LINEARID": "11017129712356", "FULLNAME": null, "RTTYP": null, "MTFCC": "S1400" }, "geometry": { "type": "LineString", "coordinates": [ [-103.91405, 31.985389], [-103.914226, 31.986221] ] } } ``` -------------------------------- ### Styling Helpers API Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/index.html Functions to help with map styling and expressions. ```APIDOC ## GET mapbox_style() ### Description Get Mapbox Style URL ### Method GET ### Endpoint /mapbox_style ## GET maptiler_style() ### Description Get MapTiler Style URL ### Method GET ### Endpoint /maptiler_style ``` -------------------------------- ### get_drawn_features() - Get Drawn Features from Map Source: https://github.com/walkerke/mapgl/blob/main/docs/reference/index.html Retrieves features that have been drawn on the map by the user or a drawing control. This function is useful for collecting user-drawn geometries for further analysis or saving. It typically requires a map instance with an active drawing control. ```javascript function get_drawn_features(map) { // Implementation to retrieve drawn features // Example: return map.getDrawingManager().getDrawnFeatures(); return null; // Placeholder } ``` -------------------------------- ### GeoJSON LineString Feature Example Source: https://github.com/walkerke/mapgl/blob/main/docs/articles/layers-overview.html This snippet shows a typical GeoJSON Feature object for a LineString geometry. It includes properties such as LINEARID, FULLNAME, RTTYP, and MTFCC. The geometry specifies the type as LineString and provides an array of coordinates. ```json { "type": "Feature", "properties": { "LINEARID": "110764080646", "FULLNAME": null, "RTTYP": null, "MTFCC": "S1400" }, "geometry": { "type": "LineString", "coordinates": [ [-103.637355, 31.826953], [-103.637358, 31.826983], [-103.637411, 31.82711] ] } } ```