A map using leaflet

Finally, we add a map to the last tab using the leaflet package. The leaflet package is an R interface to the excellent JavaScript leaflet package, which can be used to build a wide variety of maps from many different sources and annotate them with data in a number of different ways. For more details on the leaflet package, visit rstudio.github.io/leaflet/. The code is relatively simple and looks like the following:

output$map = renderLeaflet({                            #1
mapData %>% #2
filter(year == input$year[2]) %>% #3
leaflet() %>% #4
addTiles() %>% #5
setView(lng = 0, lat = 0, zoom = 2) %>% #6
addCircles(lng = ~ lon, lat = ~ lat, weight = 1, #7
radius = ~ lifeExp * 5000, #8
popup = ~ paste(country, lifeExp)) #9
})

It's not essential that you understand this code at this point, and we will be making use of the leaflet package in the rest of the book, but let's look at it line by line to get an idea of how it works:

  • Line 1: This defines output$map as containing a leaflet map so that Shiny knows how to handle the output.
  • Line 2: This tells the function to use the mapData that we already loaded right at the top of the file (not, in this case, the reactive data returned by mapData()).
  • Line 3: This filters the data so that only the most recent data given in the selection can be selected.
  • Line 4: This tells R that we want to use a leaflet.
  • Line 5: This draws the background to the map—lots of different maps are available. See ?addTiles for more help on this function.
  • Line 6: This defines which bit of the map we are looking at and how zoomed in we are. This will focus on latitude 0 and longitude 0, with the map zoomed most of the way out.
  • Lines 7 to 9: These add the actual data points; here, you can see that we give the latitude and longitude as one-sided equations, reduce the weight (pen width), and give the formula to determine the radius of the circles (life expectancy with a 5,000 scaler so it shows at the right size). Finally, we define the popup, which is what appears when you click each circle (in this case, the name of the country and the actual life expectancy).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset