Skip to contents

Set data for a source on the map

Usage

set_source_data(
  proxy,
  source_id,
  data,
  type = "geojson",
  options = list(bounds = NULL, padding = 50, max_zoom = NULL, linear = FALSE)
)

Arguments

proxy

The map proxy object created by mapProxy().

source_id

The ID of the source to update.

data

The data for the source, typically in GeoJSON format.

type

The type of the source. Default is "geojson". Other options include "vector" or "raster".

options

Additional options for updating the source data, such as:

  • bounds: Optional bounding box to fit the map to after updating the source data. Can be provided as a list of two coordinate pairs (e.g., list(c(lon1, lat1), c(lon2, lat2))) or as an sf object.

  • padding: Padding in pixels to apply when setting map bounds. Default is 50.

  • max_zoom: Maximum zoom level to allow when fitting the map to the bounds. If not provided, it will default to the map's maximum zoom level.

  • linear: Whether to use a linear animation when fitting the map to the bounds. Default is FALSE (uses a fly animation).

Value

The map proxy object for chaining.

Examples

if(interactive()){
library(shiny)
library(sf)
library(toro)

data(quakes)
quakes_data <- sf::st_as_sf(quakes, coords = c("long", "lat"), crs = 4326)

ui <- fluidPage(
 tagList(
   mapOutput("map"),
   actionButton("btn", "Update Source Data")
 )
)
server <- function(input, output, session) {
 get_random_points <- function(data, n = 10) {
   random_rows <- runif(n, min = 1, max = nrow(data))
   return(data[random_rows, ])
 }

 output$map <- renderMap({
   map() |>
     add_symbol_layer(
       id = "quakes",
       source = get_random_points(quakes_data)
     )
   })
 observe({
   mapProxy("map") |>
     set_source_data(
       source_id = "source-quakes",
       data = get_random_points(quakes_data)
     )
 }) |>
 bindEvent(input$btn)
}
}