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