knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
Leaflet is one of the most popular open-source JavaScript libraries for interactive maps. It's used by websites ranging from The New York Times and The Washington Post to GitHub and Flickr, as well as GIS specialists like OpenStreetMap, Mapbox, and CartoDB.
This R package makes it easy to integrate and control Leaflet maps in R.
sp
or sf
packages, or data frames with latitude/longitude columnsTo install this R package, run this command at your R prompt:
install.packages("leaflet") # to install the development version from Github, run # devtools::install_github("rstudio/leaflet")
Once installed, you can use this package at the R console, within R Markdown documents, and within Shiny applications.
You create a Leaflet map with these basic steps:
leaflet()
.addTiles
, addMarkers
, addPolygons
) to modify the map widget.Here's a basic example:
library(leaflet) m <- leaflet() %>% addTiles() %>% # Add default OpenStreetMap map tiles addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R") m # Print the map
In case you're not familiar with the pipe (magrittr or base) operator (%>%
/ |>
), here is the equivalent without using pipes:
m <- leaflet() m <- addTiles(m) m <- addMarkers(m, lng=174.768, lat=-36.852, popup="The birthplace of R") m
We highly recommend that you proceed to The Map Widget page before exploring the rest of this site, as it describes common idioms we'll use throughout the examples on the other pages.
Although we have tried to provide an R-like interface to Leaflet, you may want to check out the API documentation of Leaflet occasionally when the meanings of certain parameters are not clear to you.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.