Introduction

Features

  • Interactive panning/zooming
  • Compose maps using arbitrary combinations of: - Map tiles - Markers - Polygons - Lines - Popups - GeoJSON
  • Create maps right from the R console or Rstudio
  • Embed maps in knitr/ Rmarkdown documents and Shiny apps
  • Easily render spatial objects from the spof sf packages, or data frames with lattitude/longitude columns
  • Use map bounds and mouse events to drive Shiny logic
  • Display maps in non spherical mercator projections
  • Augment map features using chosen plugins from leaflet plugins repository

Installation

To install this R package, run this commnad at your R prompt

install.packages("leaflet")
## Installing package into '/home/rstudio-user/R/x86_64-pc-linux-gnu-library/3.6'
## (as 'lib' is unspecified)

Basic Usage

You create a Leaftlet map with these basic steps

  1. Create a map widget by calling leaflet().

  2. Add layers (i.e features) to the map by usind layer functions (e.g: addTiles, addMarkers, addPolygons) to modify the map widget

  3. Repeat step 2 as desired

  4. Print the map widget to display it

Here is a basis example:

library(leaflet)

m<- leaflet()%>% addTiles() %>%addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")

m #Print the map

The Map Widget

Initializing Options

  • The map widget can be initialized with certain parameters. This is achieved by populating the options argument as shown below.
leaflet(options= leafletOptions(minZoom=0,maxZoom = 18))

Map Methods

  • You can manipulate the attributes of the map widget using a series of methods. Please see the help page ?setView for details

    • setView() sets the enter of the map view and the zoom level

    • fitBounds() fits the view into the rectangle [lng1, lat1]- [lng2,lat2];

    • clearBounds() clears the bound, so that the view will be automaticaly determined by the range of latitude/ longitude data in the map layers if provided

The Data Object

Both leaflet() and the map layer functions have an optional data parameter that is designed to receive spatial data in one of several forms:

  • From base R
    • lng/ lat matric
    • data frame with lng/lat columns
  • From the sp package
    • SpatialPoints[DataFrame]
    • Line/Lines
    • SpatialLines[DataFrame]
    • Polygon/Polygons
    • SpatialPolygons[DataFrame]
  • From the **maps** packages

  • The data argument is used to derive spatial data for functions that need it; for example, if data is a SpatialPolygonsDataFrame object, then calling addPolygons on that map widget will know to add the polygons from that SpatialPolygonsDataFrame

It is straightforward to derive these variables from sp packages since they always represent spatial data in the same way. On the other hand, for a normal matrix or data frame, any numeric column could potentially contain spatial data. So we resort to guessing based on column names

- The latitude variable is guessed by looking for columns named `lat`
You can always explicity identify latitude/ longitude columns by providing `lng` and `lat` arguments to the layer function

For example, we do not specify the values for the argument lat and lng in addCircles() below, but the columns Lat and Long columns (see below for more info on the ~ syntax)

# add some circles to a map
df<- data.frame(Lat=1:10,Long=rnorm(10))

leaflet(df)%>% addCircles()    

You can also explicitly specify the Lat and Long columns (see below for more info on the ~ syntax):

leaflet(df)%>% addCircles(lng=~Long,lat=~Lat)

A map layer may use a different data object to override the data providded in leaflet(). We can rewrite the above example as:

leaflet()%>%addCircleMarkers(data=df,lat=~Lat,lng=~Long)

Using Basemaps

Leaflet supports basemaps using map tiles (setTiles()), popularized by Gooogle Maps and now used by nearly all interactive web maps

Default (OpenStreertMap) Tiles

The easiest way to add tiles is by calling addTiles() with no arguments; by default, OpenStreetMap tiles are used

Third-Party Tiles

Alternatively, many popular free third-party basemaps can be added using the addProviderTiles() function, which is implemented sing the leaflet providers plugin.

As convenience, leaflet also provides a nanmed list of all the third-party tile providers that are supported by the plugin. This enables you to use auto-completion feature of your favourite R IDE (like R studio)

Just type the providers$ and **Choose from one of the options. You can also use names(providers) to view all of the options

m %>% addProviderTiles(providers$CartonDB.Position)

## Custom Tile URL Template

If you happen to have a custom map tile URL template to use, you can provide it as an argumet to addTiles()

WMS Tiles

You can use addWMSTiles() to add WMS (Web Map Service) tiles. Tha map below shows the Base Reflectivity (a measure of the intensity of precipitation occuring) using the WMS from IOWA

leaflet() %>% addTiles() %>% setView(-93.65, 42.0285, zoom = 4) %>%
  addWMSTiles(
    "http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi",
    layers = "nexrad-n0r-900913",
    options = WMSTileOptions(format = "image/png", transparent = TRUE),
    attribution = "Weather data © 2012 IEM Nexrad"
  )

Combining Tile layers

You aren’t restricted to using a single basemap on a map; you can stack them by adding multiple tile layers. This generally only makes sense if the front tiles consist of semi transparent tiles, or have an adjusted opacity via the options argument.

m%>% addProviderTiles(providers$MtbMap)%>% addProviderTiles(providers$Stamen.TonerLines, options=providerTileOptions(opacity=0.35))%>%addProviderTiles(providers$Stamen.TonerLabels)

Markers

Use markers to call out points on the map. Marker locations are expressed in latidude/ longitude coordinates, an can either appear as icons or as circles

Data sources

Point data for markers can come from a variety of sources:

- `SpatialPoits` or `SpatialPointsDataFrame` objects (from the sp package)
- `POINT, sfc_POINT` and `sf` objects (from `sf` package); only X and Y dimensions will be considered

Example “addMarkers(lng=Longitude,lat=Latitude)”

Icon Markers

data(quakes)

leaflet(data=quakes[1:20,])%>% addTiles()%>% addMarkers(lng = ~long,lat = ~lat, popup = ~as.character(mag),label = ~as.character(mag))

Customizing Marker Icons

You canprovide custom markers in one of several ways, depending on the scenario. FOr each of these ways, the icon can be provided aseither a URL or as a file path

From the simple case of applyying a single icon to a set of markers, use makeIcon()

greenLeafIcon<- makeIcon(
  iconUrl="http://leafletjs.com/examples/custom-icons/leaf-green.png",iconWidth = 38, iconHeight = 95, iconAnchorX = 22, iconAnchorY = 94, shadowUrl = "http://leafletjs.com/examples/custom-icons/leaf-shadow.png",shadowWidth = 50,shadowHeight = 64,shadowAnchorX = 4,shadowAnchorY = 62
)

leaflet(data=quakes[1:4,])%>%addTiles()%>% addMarkers(lng = ~long, lat=~lat,icon=~greenLeafIcon)

If you have several icons to apply that vary only by a couple of couple of the parameter (same size but different character). icons function() make this like a dataframe

quakes1<- quakes[1:10,]

leafIcons<- icons(
  leafIcons <- icons(
    iconUrl = "http://leafletjs.com/examples/custom-icons/leaf-green.png",
    "http://leafletjs.com/examples/custom-icons/leaf-red.png"
  ), iconWidth = 38, iconHeight = 95,
  iconAnchorX = 22, iconAnchorY = 94,
  shadowUrl = "http://leafletjs.com/examples/custom-icons/leaf-shadow.png", shadowWidth = 50, shadowHeight = 64, shadowAnchorX = 4,shadowAnchorY = 62
)

leaflet(data=quakes1)%>% addTiles()%>% addMarkers(lng=~long,lat=~lat,icon=leafIcons)