Leaflet Heat Maps

Create Map

We start by creating a map of the location.

L2 <- Leaflet$new()
L2$setView(c(29.7632836,  -95.3632715), 10)
L2$tileLayer(provider = "MapQuestOpen.OSM")

Get Data

We will use the crime dataset from the ggmap package that contains a tidied up version of Houston crime data from January 2010 to August 2010.

data(crime, package = 'ggmap')
crime_dat = ddply(crime, .(lat, lon), summarise, count = length(address))
crime_dat = toJSONArray2(na.omit(crime_dat), json = F, names = F)

Add HeatMap

Now that we have the map and the data, the next step is to add the data to the map as a heatmap layer. Thanks to the Leaflet.heat plugin written by the Vladimir Agafonkin, the author of LeafletJS, this is really easy to do, with a little bit of custom javascript.

# Add leaflet-heat plugin. Thanks to Vladimir Agafonkin
L2$addAssets(jshead = c(

# Add javascript to modify underlying chart
L2$setTemplate(afterScript = sprintf("
  var addressPoints = %s
  var heat = L.heatLayer(addressPoints).addTo(map)           
", rjson::toJSON(crime_dat)


Note that it is easy to abstract away these additional steps into a method for the Leaflet class, or an R function that only needs to be provided the data.