leaflet packageThis document illustrates the basic use of the leaflet package. More comprehensive information is in RStudio’s introduction to the package. The leaflet() function produces an html widget which can be nicely embedded into webpages. We build the widget by adding different layers. A ‘map’ layer can be added using function addTiles().
library(leaflet)
leaflet() %>% addTiles()
It shows a default map. There are lots of different maps that you can use. They are available here. Below I use a topographic map and center it on the capital region.
library(leaflet)
leaflet() %>% addProviderTiles("OpenTopoMap") %>% setView(-73, 42, zoom = 4)
We can add things to the map. For example, below I add a marker for Brown School in Schenectady. (This is where ESYO has its rehearsal.)
leaflet() %>%
addTiles() %>%
addMarkers(lat= 42.783565, lng=-73.9005059)
If I would like to label that marker I add a pop-up.
leaflet() %>%
addTiles() %>%
addPopups(lat= 42.783565, lng=-73.9005059, "Brown School")
Rather adding things to a map one by one, we may want to add a whole data set of things. Let plot the addresses of ESYO musicians so that their parents can find other musicians nearby for carpooling. I put the data on dropbox and stripped out musicians’ last names, phone numbers and addresses to protect their privacy. I included longitude and latitude which I obtained by feeding the addresses to function geocode() from package ggmap
musicians <- read.csv("https://www.dropbox.com/s/9f5fcskncz78kho/musicians.csv?raw=1")
head(musicians)
## First.Name Ensemble Instrument lat lon
## 1 Ishan Repertory Oboe 42.71977 -73.73454
## 2 Carly Repertory Percussion 42.67451 -73.89643
## 3 Anna Repertory Violin 42.74187 -73.75390
## 4 Caroline Repertory Violin 42.77225 -73.73299
## 5 Logan Repertory Trumpet 42.64105 -73.78483
## 6 Avery Repertory Bassoon 42.62037 -73.62357
leaflet() %>%
addTiles() %>%
addCircleMarkers(~lon, ~lat, data=musicians)
Let’s add popup info that appear when circle marker is clicked. The content of the pop-up can be html. I want name and instrument. Let’s create that content. In order for the instrument to appear on a second line we include html tab <\br>
musicians$popupcontent <- paste(musicians$First.Name, "<br/>" , musicians$Instrument )
leaflet() %>%
addTiles() %>%
addCircleMarkers(~lon, ~lat, data=musicians, popup = ~popupcontent, stroke = FALSE, fillOpacity = 0.75)
Finally, let’s color code the different ensembles and add a legend. I moved data to the first call of leaflet so that it can apply to all layers.
pal <- colorFactor(c("navy", "red"), domain = c("Repertory", "Youth"))
leaflet(data=musicians) %>%
addTiles() %>%
addCircleMarkers(~lon, ~lat, popup = ~popupcontent, stroke = FALSE,
fillOpacity = 0.75, color = ~pal(Ensemble)) %>%
addLegend(pal=pal, values = ~Ensemble, title="Ensemble____")
## Warning in doColorRamp(colorMatrix, x, alpha, ifelse(is.na(na.color), "", :
## '.Random.seed' is not an integer vector but of type 'NULL', so ignored