I had three requirements for myself:
- Write code that created an interactive web map using Leaflet
- Use Shapefile data about the City of Toronto
- Allow anyone to run it on their machine, without having to download or extract data
The code is below, followed by the result. Not a bad result for only 10 or 15 lines!
# MAPPING THE TORONTO SUBWAY LINES USING R & Leaflet # -------------------------------------------------- # # Myles M. Harrison # http://www.everydayanalytics.ca #install.packages('leaflet') #install.packages('maptools') library(leaflet) library(htmlwidgets) library(maptools) # Data from Toronto's Open Data portal: http://www.toronto.ca/open # Download the file and read in the data_url <- "http://opendata.toronto.ca/gcc/TTC_subway%20lines_wgs84.zip" cur_dir <- getwd() temp_dir <- tempdir() setwd(temp_dir) download.file(data_url, "subway_wgs84.zip") unzip("subway_wgs84.zip") sh <- readShapeLines("subway_wgs84.shp") unlink(dir(temp_dir)) setwd(cur_dir) # Create a categorical coloring function linecolor <- colorFactor(rainbow(16), sh@data$SBWAY_NAME) # Plot using leaflet m <- leaflet(sh) %>% addTiles() %>% addPolylines(popup = paste0(as.character(sh@data$SBWAY_NAME)), color=linecolor(sh@data$SBWAY_NAME)) %>% addLegend(colors=linecolor(sh@data$SBWAY_NAME), labels=sh@data$SBWAY_NAME) m # Save the output saveWidget(m, file="TTC_leaflet_map.html")