9 Maps
9.1 Leaflet
To create interactive maps you need the leaflet library. This provides various functions that will be transalated into Javascript.
9.1.1 Display a basic map
## Warning: package 'leaflet' was built under R version 3.4.4
mymap <- leaflet::leaflet() # This initiates a map; it is possible to change the width and height here
mymap <- leaflet::setView(mymap,
lng = -0.12481, # The initial longitude + latitude
lat = 51.50811,
zoom = 10) # The initial zoom level
mymap <- leaflet::addTiles(mymap) # This add tiles to the map; by default it uses OpenStreetMap
mymap # this will display the map9.1.2 Add markers, shapes and popups to a map
mymap <- leaflet::addMarkers(mymap, lng=-0.126965, lat=51.501555, popup="HMRC") #Use longitude and latitude to place a marker. The default blue marker is used.
mymap <- leaflet::addCircles(mymap, lng=-0.021002, lat=51.504475,radius=10, popup="HMRC") #Use longitude and latitude to place a circle, and radius (in metres) for its size.
mymap9.1.3 Add Boundaries
To add boundaries you need geojson or topojson. This needs to be converted into a format the R understands using functions in the geojsonio library.
R converts this geojson into a Spatial Polygon Dataframe (SPD). This should consist of 2 main attributes: data which has descriptive information about the polygon such as a name, and polygons and contains all the coordinates for each polygon. To see what the contain you can us the following:
The boundary data can now be attached to the map when it is first initialized.
9.1.4 Add Interactivity
Highlights can be added when you hover over an area.
mymap <- leaflet::addPolygons(mymap,
color='black',
weight=1,
fillColor='white',
fillOpacity = 0.8 ,
highlight = highlightOptions(
weight = 2,
color = "red",
bringToFront = TRUE)
)Popup info can also be added when you hover over an area. This requires using the sprintf function, which includes HTML.
mylabel <- sprintf("<strong>%s</strong><br/>%s", la$lad16nm, la$lad16cd ) %>% lapply(htmltools::HTML)
# These can can now be assigned to the label attribute
mymap <- leaflet::addPolygons(mymap, color='black',weight=1, fillColor='white',fillOpacity = 0.8,
highlight = highlightOptions(
weight = 2,
color = "red",
bringToFront = TRUE),
label = mylabel)The code that is written in the sprintf function rquires a special format. The first argument defines what and how text willl be dispalayed. It includes placeholders (eg. %s) that can have differnet types. All subsequent arguments represent the data variables that will are represented by the placeholders (in the order they occur).For more info see https://www.rdocumentation.org/packages/base/versions/3.4.3/topics/sprintf.
9.1.5 Attach extra information to your boundary dataset
You will usually want to add additional data/statistics to the boundary file, so that you can improve visualition/interactivity. You can merge a regular dataframe wih an SPD provided they have a common variable (eg. ONS Id’s).
# First create a dataframe with test data
mydf <- data.frame('lad16cd'=c('E06000001','E06000002','E06000003'),
'extraStat'=c(25000,34000,38000) )
# Merge extra data into the SPD
require(sp) # Need for the following merge to work correctly
la <- sp::merge(la, mydf, by.x = "lad16cd", by.y = "lad16cd")
#Check that merge has worked
la@data # A new column should appear with the extra data 9.1.6 Add colour based on area data
First you will need to define a colour pallete, and the range of values (bins) they will apply to. This is done using the colorBin function.
pal <- leaflet::colorBin("YlOrRd", bins = c(0, 24999, 34000, 38000, Inf))
# 'YlorRd' is a particular color scale. See http://colorbrewer2.org for alternatives. You could also create a user defined list of colours using Hexadecimal eg. #fcbba1 instead. Now the colour pallete can be assigned to the fillColor attribute, allomg with the variable name that will be used .
9.2 Inserting HTML & Javascript directly into R
Instead of using packages to create javavscript, you can insert javascript directly into Rmarkdown, and it should be displayed correctly when it Knitr is used.
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.0-rc.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.0.0-rc.3/dist/leaflet.js"></script>
<script type="text/javascript" src="https://stamen-maps.a.ssl.fastly.net/js/tile.stamen.js"></script>
<div id="mapid"></div>
// Define Map area/position and any background tiles
var map = new L.Map('mapid', { center: new L.LatLng(53.10, -1.26),zoom: 7 });
var layer = new L.StamenTileLayer("terrain");
map.addLayer(layer);