Maps with Leaflet

Introduction

Maps

Getting started

The leaflet equivalent of the ggplot function is leaflet:

For example, NASA’s earth at night map:

Or CartoDB’s “Positron” map (nice if you want the map elements to be “light”):

Custom data and markers

Here are the rules for your table:

  • Latitudes should be in column named “lat” or “latitude”
  • Longitudes should be in a column named “lon”, “lng”, “long” or “longitude”

We can make a simple map as before, but this time we specify the data argument in our call to leaflet:

Nothing’s changed; but now we can use the additional columns to add annotations onto our map, like markers:

Assuming "lon" and "lat" are longitude and latitude, respectively

If you have a lot of markers in one place the clustering feature can be useful (note the lower zoom level):

Assuming "lon" and "lat" are longitude and latitude, respectively

You can also add two different kinds of “circles” onto your maps to visualize quantitative data. The first is addCircleMarkers:

Assuming "lon" and "lat" are longitude and latitude, respectively

The second addCircles:

Assuming "lon" and "lat" are longitude and latitude, respectively

The difference between the two is that the quantitative variable being used for the radius different things:

  • In addCircleMarkers it specifies the size in pixels (image-land); no matter the zoom the circles are always the same size
  • In addCircles it specifies the size in meters (real-world); so they get bigger or smaller when you zoom.

Leaflet with Shiny

Here’s an example:

ui.R

server.R

server.R

function(input, output, session) {
  
  lats <- -90:90
  lons <- -180:180
  
  output$worldMap <- renderLeaflet({
    leaflet() %>% 
      setView(lng = -79.442778, lat = 37.783889, zoom = 5) %>% 
      addTiles()
  })
  
  observe({
    # note the dummy use of the action button input
    btn <- input$newButton
    
    leafletProxy("worldMap") %>%
      setView(lng = sample(lons, 1), lat = sample(lats, 1), zoom = 5)
  })
  
}
<environment: 0x56485a2a6df8>