2017-06-13 95 views
0

addCirclemarkers中插入弹出窗口导致需要映射数千个点的数据的冗长计算时间。我假设在显示地图之前必须计算所有弹出窗口。r闪亮的传单 - 按需创建弹出窗口

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

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)) 

回答

0

有了你的代码event$idNULL,所以sgh <- pts2[row.names(pts2) == event$id,]线返回NULL为好。

你必须在layerId添加到CircleMarkers(而没有必要将其添加到Popup
这也让访问它wothout需要对“合并”它与原始数据:

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) 
    }) 
}) 
+0

然后,您可能需要像以前一样“合并”原始数据('event $ id'现在包含原始数据的'name'值) – GGamba

+0

非常感谢!如果我想要使用更多数据例如,如果数据中会有第三列,比如“type”= c(“great”,“far away”,“popular”),那么我怎样才能显示“这是place 1,它是雷尔好极了“。 –

+0

似乎你在我删除我之前的评论之前回复了。 ;) –