remove leaflet heatmap layer with rCharts and shiny

元气小坏坏 提交于 2019-12-01 07:17:02

问题


I want to be able to let users see different heatmaps based on a parameter's choice in shiny, using rCharts and Leaflet.

The first time the heatmap is displayed it looks great.
All the other times the heat map is displayed as layers on top of the first one.

How to reset the leaf map so that only the current layer / heat map is displayed?

This sample code is based on the notorious Ramnath's Houston crime demo.

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:


The answer to my problem has been given brilliantly by paulyeno.

This piece of javascript substitute the lines above:

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

Please note that currently the above code runs in shiny 0.10.1 but not in 0.10.2.1 (bug reported to shiny & rCharts)



来源:https://stackoverflow.com/questions/26752589/remove-leaflet-heatmap-layer-with-rcharts-and-shiny

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!