“按需”一一创建弹出窗口

问题描述 投票:0回答:1

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))
r shiny r-leaflet
1个回答
0
投票

您的代码

event$id
NULL
,因此
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)
    })
})
© www.soinside.com 2019 - 2024. All rights reserved.