r闪亮的传单 - 按需创建弹出窗口'

时间:2017-06-13 07:37:04

标签: r shiny leaflet

addCirclemarkers中插入弹出窗口会导致数千个要映射的点数据的计算时间过长。我假设在显示地图之前必须计算所有弹出窗口。

如果点击了一个点/圆圈/标记,我在线搜索了一种只添加/创建弹出窗口的方法。目前,我在下面的代码。如果运行此代码,您将看到弹出窗口已创建,但未显示从数据中提取的字符串。我做错了什么?

library(shiny)
library(leaflet)
library(htmltools)
library(sp)

data <- data.frame(
  "name"=c("Place 1","Place 2","Place 3"),
  "lat"=c(50,51,52),
  "lng"=c(3,4,5), stringsAsFactors = FALSE)

ui = fluidPage(
  fluidRow(column(8, offset = 2, leafletOutput("map", width = "100%", height = "650px")))
  )                             

server = function(input, output, session) {

  pts <- reactive({
    pts <- data
    coordinates(pts) <- ~lng+lat
    pts
  })

  output$map <- renderLeaflet({
    leaflet(pts()) %>%
      addTiles(group="OSM") %>%
      addCircleMarkers()
  })

  observeEvent(input$map_marker_click, {
    leafletProxy("map") %>% clearPopups()
    event <- input$map_marker_click
    if (is.null(event))
      return()
    isolate({
      pts2 <- pts()
      sgh <- pts2[row.names(pts2) == event$id,]
      # sgh <- pts2[pts2$name == event$id,]
      content <-  htmlEscape(paste("This place is",as.character(sgh$name)))
      leafletProxy("map") %>% addPopups(event$lng, event$lat, content, layerId = event$id)
    })
  })

}

shinyApp(ui = ui, server = server, options = list(launch.browser=TRUE))

1 个答案:

答案 0 :(得分:0)

您的代码event$idNULL,因此sgh <- pts2[row.names(pts2) == event$id,]行也会返回NULL

您必须将layerId添加到CircleMarkers(并且无需将其添加到Popup
这也允许访问它,而不需要将其与原始数据“合并”:

output$map <- renderLeaflet({
    leaflet(pts()) %>%
        addTiles(group="OSM") %>%
        addCircleMarkers(layerId = ~name)
})

observeEvent(input$map_marker_click, {
    leafletProxy("map") %>% 
        clearPopups()
    event <- input$map_marker_click
    if (is.null(event))
        return()
    isolate({
        content <-  htmlEscape(paste("This place is", event$id))

        leafletProxy("map") %>% 
            addPopups(event$lng, event$lat, content)
    })
})