library(rgdal)
library(leaflet)
library(RColorBrewer)
library(raster)
library(maptools)
library(htmlwidgets)
# read in data
nc <- readShapeSpatial(system.file("shapes/sids.shp",
package="maptools")[1],
proj4string=CRS("+init=epsg:4326"))
# download leaflet basemap
map <- leaflet() %>% addTiles('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')
# plot map
map
# add layers
map %>% addPolygons(data = nc)
# Generate a color code for administrative units
Colors<-brewer.pal(4,"OrRd")
SID74_Cat<-as.numeric(cut(nc$SID74,breaks=c(0,2,4,8,45),include.lowest=T))
SID_Cols<-Colors[SID74_Cat]
# Make popup
nc_leaflet<-leaflet() %>% addTiles('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
attribution = paste(
'© OpenStreetMap contributors',
'© CartoDB'
)
) %>% addPolygons(data=nc, popup=paste(sep = "
",
"","SIDs deaths 1974","",
nc$SID74),
color = "gray",
fillColor=SID_Cols,
opacity=0.8,
fillOpacity = 0.6,
weight=2, group="Counties")
# plot
nc_leaflet
# Save html file to share
saveWidget(widget = nc_leaflet, file = "C:\\Users\\sturrockh\\Documents\\Work\\teaching\\Spatial Epi UCSF\\nc_leaflet.html")
# Add other types of data
elevation_USA <- getData('alt', country="USA")[[1]]
elevation_nc <- mask(elevation_USA[[1]], nc)
nc_leaflet %>% addRasterImage(elevation_nc, group="Elevation") %>% addLayersControl(overlayGroups=c("Counties", "Elevation"))
# Check out http://leaflet-extras.github.io/leaflet-providers/preview/ for other basemap options
# for example
nc_leaflet<-leaflet() %>% addTiles('http://{s}.tile.thunderforest.com/spinal-map/{z}/{x}/{y}.png') %>%
addPolygons(data=nc, popup=paste(sep = "
",
"","SIDs deaths 1974","",
nc$SID74),
color = "gray",
fillColor=SID_Cols,
opacity=0.8,
fillOpacity = 0.6,
weight=2, group="Counties")
nc_leaflet