我正在尝试创建一个闪亮的应用程序,允许用户单击地图中的一个点,用标记显示他们单击的位置,允许他们用名称标记该点(他们输入自由文本)然后将他们添加的所有点的纬度、经度和标签/名称保存到 data.frame 中,可以使用下载按钮将其导出为 .csv。
我已经弄清楚如何记录标签,使用
textInput()
并在他们按下回车键时提交标签(使用我从另一个 S/O 帖子复制的 java 代码)。然后他们在地图上点击他们想要添加标记的地方,标记被添加为leafletProxy()
并且他们添加的最后一个标签被自动分配 - 这有点笨拙,因为他们必须删除地图中的文本框输入下一个标签,但我稍后会尝试弄清楚如何对其进行排序。
我的主要问题是我无法弄清楚如何将纬度、经度和分配的标记标签提取到
data.frame()
。为此,我需要了解 input$map_click
的结构,但我似乎无法在任何地方找到它 - 我知道这是一系列列表,但不知道我想提取的三件事在哪里。理想情况下,我还想在地图下方的 Shiny 应用程序中显示表格,并在每次添加点时更新新行。
更一般地说,当涉及到 Shiny 时,我仍然是一个新手,我想了解如何在开发期间在我的 r 控制台中基于用户交互查看在应用程序中创建的东西的结构(例如在这个案例如何在我的 r 环境中保存
input$map_click
的副本,以便我可以检查它)。
这里是一些示例代码:
# Load libraries ----------------------------------------------------------
# Check if pacman is installed, install if not:
if (!require("pacman")) install.packages("pacman")
# Use pacman::p_load to load required packages:
pacman::p_load(shiny,
DT,
here,
rio,
dplyr,
sf,
leaflet)
# Create UI ---------------------------------------------------------------
ui <- fluidPage(
# Create a title for the page:
title = "Localisation des nouveau quartiers" ,
# Place title in the centre:
position = "static-top",
# Add extra javascript to record when enter key is pressed:
tags$script('
$(document).on("keyup", function(e) {
if(e.keyCode == 13){
Shiny.onInputChange("keyPressed", Math.random());
}
});
'),
# Set output as leaflet map:
leafletOutput("map"),
# Create text box for GPS point label:
textInput(inputId = "nom_du_point",
label = "Proposer un nom pour votre nouveau quartier",
value = "",
width = "100%"),
# Add table of coordinates:
DTOutput(outputId = "quartier_centroids")
)
server <- function(input, output, session) {
# Render the leaflet map:
output$map <- renderLeaflet(
leaflet() %>%
# Add open street map (default base layer)
addTiles(options = tileOptions(maxZoom = 18)) %>%
)
# Record label entered by user:
gpslabel <- reactiveVal()
observeEvent(input[["keyPressed"]], {
gpslabel(input[["nom_du_point"]])
# Clear the text input to allow for a new label:
updateTextInput(session,
inputId = "service",
value = "")
})
# Add new markers to map by user clicking:
observeEvent(input$map_click, {
# Add coordinates on click:
click <- input$map_click
# Add marker and label to the map using coordinates and text entry:
leafletProxy('map') %>%
addMarkers(lng = click$lng,
lat = click$lat,
label = gpslabel())
# Add table showing results under map:
output$quartier_centroids <- renderDT({
DT::datatable(click, editable = TRUE)
})
})
}
# Run the application
shinyApp(ui = ui, server = server)
请注意,这段代码允许我为一个点添加标签/名称,然后在地图上放置一个图钉,地图上会自动分配最后一个标签。但是表格没有显示在底部,并给我这个错误:
Error: data must be 2-dimensional (e.g. data frame or matrix)
我假设这是因为
click
是一个列表,我不知道访问列表的哪些部分来获取纬度、经度和标签。