使用rCharts删除传单热图图层并闪亮

时间:2014-11-05 08:26:59

标签: r leaflet shiny heatmap rcharts

我希望能够让用户使用rCharts和Leaflet根据参数的闪亮选择看到不同的热图。

第一次显示热图时,它看起来很棒 所有其他时间热图在第一个上面显示为图层。

如何重置叶子图以便只显示当前图层/热图?

此示例代码基于臭名昭着的Ramnath's Houston犯罪演示。

library(shiny)
library(rCharts)
library(rjson)
library(data.table)
##   
crimedt <- as.data.table(na.omit(ggmap::crime[,c("address","offense","lon","lat")]))
crimedt <- crimedt[,offense:=as.character(offense)]
setkey(crimedt, lat,lon,offense)
crime_cdt <- crimedt[, .(count = length(address))
                          , by = .(lat,lon,offense)]
setkey(crime_cdt,offense)
seLabels <- unique(crime_cdt$offense)

#
runApp(list(
  ui =   tabPanel("main", fluidPage(
    h4("Crime hotmap"),
    column(3,
    selectInput("slCrime", "Choose Crime Type:",
                                            seLabels, seLabels[1])
    ),
    column(9,
           chartOutput('baseMap','leaflet'),
           tags$style('.leaflet {height: 500px;}'),
           tags$head(tags$script(src="http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js"))
            , uiOutput('datamap')
    )
  )),
server = function(input, output, session) {
output$baseMap<-renderMap({
baseMap <- Leaflet$new()
mlon <- mean(crime_cdt$lon)
mlat <- mean(crime_cdt$lat)
baseMap$setView(c(mlat,mlon),9)
baseMap$tileLayer(provider="OpenStreetMap")
baseMap
 })
output$datamap<-renderUI({ 
    if(is.null(input$slCrime)) { return() }
    q = quote(input$slCrime)
    crime_cdt <- crime_cdt[eval(q), .(lat, lon, count)]
    maxdat <- max(crime_cdt$count)
  arrdat <- toJSONArray2(crime_cdt, json=F, names=F)
  jsdat <- rjson::toJSON(arrdat)

tags$body(tags$script(HTML(sprintf("
var addressPoints = %s
var maxval = %f
var heat = L.heatLayer(addressPoints, {maxZoom: 9, radius: 20, blur: 40}).addTo(map)
 </script>",  jsdat, maxdat
))))
})
}
))

1 个答案:

答案 0 :(得分:1)

我的问题的答案已由paulyeno 出色地

这段javascript代替上面的行:

tags$body(tags$script(HTML(sprintf("
var addressPoints = %s
if (typeof heat === typeof undefined) {
            heat = L.heatLayer(addressPoints, {maxZoom: 9, radius: 20, blur: 40})
            heat.addTo(map)
          } else {
            heat.setOptions({maxZoom: 9, radius: 20, blur: 40})
            heat.setLatLngs(addressPoints)
          }
 </script>",  jsdat

请注意,目前上面的代码在闪亮的0.10.1中运行,但在0.10.2.1中运行(错误报告为闪亮的&rCharts)