# 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 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.

``````library(shiny)
library(leaflet)
library(raster)

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

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

server <- function(input, output, session) {
output\$map <- renderLeaflet({
# Create leaflet map
leaflet() %>%
targetGroup='draw',
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") %>%
as.matrix()

# 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
showModal(modalDialog(
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.