检索 Shiny APP 传单地图中所有标记的位置

Retrieve positions of all markers in a leaflet map of Shiny APP

我有一张传单地图,其中包含可拖动的标记和形状、用户绘制的功能(带有 leaflet.draw 插件)。现在我想以编程方式从传单地图中检索 layer/group 中的所有功能。

这个功能应该怎么实现?感谢您的任何建议。

这里我提供了一个简单的例子,一组随机的标记被添加到leaflet map中,组为markers(代码直接从https://rstudio.github.io/leaflet/shiny.html复制并做了一些修改)。我的目标是检索所有新标记的位置。

我真正的问题是多边形,可能比这个复杂,但方法应该类似。

library(shiny)
library(leaflet)

r_colors <- rgb(t(col2rgb(colors()) / 255))
names(r_colors) <- colors()

ui <- fluidPage(
  leafletOutput("mymap"),
  p(),
  actionButton("recalc", "New points"),
  verbatimTextOutput('summary')
)

server <- function(input, output, session) {

  points <- eventReactive(input$recalc, {
    cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)
  }, ignoreNULL = FALSE)

  output$mymap <- renderLeaflet({
    leaflet() %>%
      addProviderTiles("Stamen.TonerLite",
                       options = providerTileOptions(noWrap = TRUE)
      ) %>%
      addMarkers(data = points(), group = 'markers')
  })

  output$summary <- renderPrint({
    # Add some codes here
    # .....

  })
}

shinyApp(ui, server)

要从地图对象中获取点,您仍然可以使用 reactiveValues() 来存储地图对象,并通过 observe() 按下按钮来更新它。然后你可以访问它的所有属性。

library(shiny)
library(leaflet)

r_colors <- rgb(t(col2rgb(colors()) / 255))
names(r_colors) <- colors()

ui <- fluidPage(
    leafletOutput("mymap"),
    p(),
    actionButton("recalc", "New points"),
    verbatimTextOutput('summary')
)

server <- function(input, output, session) {

    rv <- reactiveValues()
    rv$m <- NULL
    rv$p <- NULL

    points <- eventReactive(input$recalc, {
        cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)
    }, ignoreNULL = FALSE)

    output$mymap <- renderLeaflet({
        m <- leaflet() %>%
            addProviderTiles("Stamen.TonerLite",
                    options = providerTileOptions(noWrap = TRUE)) %>%
            addMarkers(data = points(), group = 'markers')
        rv$m <- m
        return(m)
    })

    observe({
        input$recalc
        ## I'm 90% confident these are the arguments you want...
        rv$p <- data.frame(x = rv$m$x$calls[[2]]$args[[1]],
                           y = rv$m$x$calls[[2]]$args[[2]])
    })

    output$summary <- renderPrint({
        # print points
        rv$p
    })
}

shinyApp(ui, server) 

旧解

我把它留在这里,因为它可能对其他人仍然有用

您可以利用 reactiveValues() 存储您的 point 数据,然后将该数据输出到您的 print

server <- function(input, output, session) {

  rv <- reactiveValues()
  rv$points <- cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)

  observe({

    if(input$recalc){
      p <-  cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)
      rv$points <- p
    }
  })

  output$mymap <- renderLeaflet({
    leaflet() %>%
      addProviderTiles("Stamen.TonerLite",
                       options = providerTileOptions(noWrap = TRUE)
      ) %>%
      addMarkers(data = rv$points, group = 'markers')
  })

  output$summary <- renderPrint({
    # Add some codes here
    # .....
    rv$points
  })
}
shinyApp(ui, server)