使用rCharts在r中创建Leaflet热图并闪亮

时间:2014-06-17 21:19:00

标签: r leaflet shiny heatmap rcharts

我正在使用Ramnath Vaidyanathan在http://rmaps.github.io/blog/posts/leaflet-heat-maps/index.html的精彩演示,我想为我的闪亮应用再现他的热图。

当我尝试使用Ramnath的代码时,虽然我只设法将地图输出,但不是热图。 可能我的问题的一部分原因是Ramnath的原始代码使用rMaps而我正在使用rCharts(也是由Ramnath开发),因为它更加发达/更好地与闪亮集成,当然还包括Leaflet。我试图将rMaps与闪亮的HTML通用命令renderUIhtmlOutput一起使用,但没有成功。

这是闪亮的代码不起作用(它只显示忽略热点库的地图):

library(rCharts)
library(shiny)

runApp(
list(ui = (pageWithSidebar(
headerPanel("Heatmap"),
sidebarPanel( width=2),
mainPanel(
mapOutput("leafmap")
)
)),
server = function(input, output) {
output$leafmap  <- renderMap({
L2 <- Leaflet$new()
L2$setView(c(29.7632836,  -95.3632715), 10)
L2$tileLayer(provider = "MapQuestOpen.OSM")
data(crime, package = 'ggmap')
library(plyr)
crime_dat = ddply(crime, .(lat, lon), summarise, count = length(address))
crime_dat = toJSONArray2(na.omit(crime_dat), json = F, names = F)
L2$addAssets(jshead = c(
 "http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js"
 ))
L2$setTemplate(afterScript = sprintf("
                                 <script>
                                 var addressPoints = %s
                                 var heat = L.heatLayer(addressPoints).addTo(map)           
                                 </script>
                                 ", rjson::toJSON(crime_dat)
 ))

L2
})
}
))

1 个答案:

答案 0 :(得分:4)

将我的评论转换为答案(making use of this question/answer

library(rCharts)
library(shiny)
library(data.table)

runApp(
  list(ui = (pageWithSidebar(
    headerPanel("Heatmap"),
    sidebarPanel( width=2),
    mainPanel(
      chartOutput("baseMap", "leaflet"),
      tags$style('.leaflet {height: 500px;}'),
  tags$head(tags$script(src="http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js")),
      uiOutput('heatMap')
    )
  )),
  server = function(input, output) {

    data(crime, package="ggmap")
    crime <- as.data.table(crime)

    output$baseMap  <- renderMap({
      baseMap <- Leaflet$new()
      baseMap$setView(c(29.7632836,  -95.3632715), 10)
      baseMap$tileLayer(provider = "MapQuestOpen.OSM")
      baseMap
    })

    output$heatMap <- renderUI({

      ## changed to use data.table for speed
      crime_dat <- crime[(lat != ""), .(count = .N), by=.(lat, lon)]
          ## there's a blank in there somewhere

      ## I was having issues with toJSON, so I'm creating my own JSON
      j <- paste0("[",crime_dat[,lat], ",", crime_dat[,lon], ",", crime_dat[,count], "]", collapse=",")
      j <- paste0("[",j,"]")

      tags$body(tags$script(HTML(sprintf("
                      var addressPoints = %s
                      var heat = L.heatLayer(addressPoints).addTo(map)"
                                         , j
      ))))

    })
  }
  ))

并显示它正常工作

enter image description here