Raster zonal statistics calculation problem

I am trying to create a shiny app where the user will draw a polygon or a line on a raster and then the app will calculate the zonal statistics.

However when trying to run the app I get the following error :slight_smile:

Warning: Error in h: error in evaluating the argument 'x' in selecting a method for function 'as.matrix': object 'getJson' not found
1: runApp

I have the whole code attached below.


# Load sample data

raster <- ("C:/Users/KS43772/Documents/DEM.tif")

ui <- fluidPage(
  actionButton("calculate", "Calculate Zonal Statistics")

server <- function(input, output, session) {
  output$map <- renderLeaflet({
    # Create leaflet map
    leaflet() %>%
      addTiles() %>%
      addRasterImage(raster) %>%
        polylineOptions = NULL,
        circleOptions = NULL,
        rectangleOptions = NULL,
        markerOptions = NULL,
        polygonOptions = NULL,
        editOptions = NULL
  # Calculate zonal statistics when button is clicked
  observeEvent(input$calculate, {
    # Get drawn polygon
    drawn <- leafletProxy() %>%
      getGroup("draw") %>%
      leaflet:::getJson() %>%
      purrr::pluck("features", 1, "geometry", "coordinates") %>%
    # Convert to SpatialPolygons object
    poly <- SpatialPolygons(list(Polygons(list(Polygon(drawn)), ID=1)))
    # Extract zonal statistics
    stats <- extract(r, poly, na.rm=TRUE)
    # Show results
      title = "Zonal Statistics",
      paste0("Mean: ", mean(stats), "<br>",
             "Median: ", median(stats), "<br>",
             "Max: ", max(stats), "<br>",
             "Min: ", min(stats), "<br>",
             "NAs: ", sum(is.na(stats)))
shinyApp(ui, server)

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.