Skip to content

Instantly share code, notes, and snippets.

@walkerke
Created August 19, 2024 19:37
Show Gist options
  • Save walkerke/1e8f86a1790a2ee98520e7bb797d6bc5 to your computer and use it in GitHub Desktop.
Save walkerke/1e8f86a1790a2ee98520e7bb797d6bc5 to your computer and use it in GitHub Desktop.
library(shiny)
library(bslib)
library(mapgl)
library(sf)
ui <- page_fluid(
theme = bs_theme(version = 5, bootswatch = "flatly"),
h2("mapgl Drawing Demo"),
layout_sidebar(
sidebar = sidebar(
width = 300,
downloadButton("download_features", "Download GeoJSON", class = "btn-success")
),
layout_column_wrap(
width = 1/2,
mapboxglOutput("map", height = "600px"),
verbatimTextOutput("feature_info")
)
)
)
server <- function(input, output, session) {
output$map <- renderMapboxgl({
mapboxgl(
center = c(13.4050, 52.5200), # Longitude and latitude for Berlin
zoom = 10
) %>%
add_draw_control()
})
output$feature_info <- renderPrint({
features <- get_drawn_features(mapboxgl_proxy("map"))
if (!is.null(features) && nrow(features) > 0) {
print(features)
} else {
"No features drawn yet."
}
})
output$download_features <- downloadHandler(
filename = function() {
"drawn_features.geojson"
},
content = function(file) {
features <- get_drawn_features(mapboxgl_proxy("map"))
if (!is.null(features) && nrow(features) > 0) {
st_write(features, file, driver = "GeoJSON")
} else {
file.create(file) # Create an empty file if no features are drawn
}
}
)
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment