I would like to display the polygon of Canada on a leaflet map.
# create map
library(leaflet)
m = leaflet() %>% addTiles()
m
I was able to find the polygon for Canada: http://www.gadm.org/country. I chose the SpatialPolygonsDataFrame format for R, but there are other formats available (such as Shapefile)
# load object in R
load("country_polygons/CAN_adm0.RData")
pol_can <- gadm
How can I display the shape on the map? I assume I have to leverage the sp package but I could not figure out how to do so.
You can pass a SpatialPolygons*
object to the addPolygons
function as per Section 2.2 of the docs here.
For example (note that the following includes a ~11.4 MB download):
library(sp)
download.file('http://biogeo.ucdavis.edu/data/gadm2/R/CAN_adm0.RData', f <- tempfile())
load(f)
leaflet() %>% addTiles() %>% addPolygons(data=gadm, weight=2)
Note that GADM data can also be downloaded with the getData
function in the raster
package:
library(raster)
can <- getData('GADM', country='VAT', level=0)
EDIT
In response to the comments, I really like the lightweight polygon datasets that Natural Earth provides. Here's an example where I download the 1:50,000,000 countries shapefile (Admin 0) from Natural Earth, subset it to the current members of the Commonwealth of Nations, and plot those. The zipped shapefile is under 1 MB.
library(rgdal)
library(leaflet)
download.file(file.path('http://www.naturalearthdata.com/http/',
'www.naturalearthdata.com/download/50m/cultural',
'ne_50m_admin_0_countries.zip'),
f <- tempfile())
unzip(f, exdir=tempdir())
world <- readOGR(tempdir(), 'ne_50m_admin_0_countries', encoding='UTF-8')
commonwealth <- c("Antigua and Barb.", "Australia", "Bahamas", "Bangladesh",
"Barbados", "Belize", "Botswana", "Brunei", "Cameroon", "Canada", "Cyprus",
"Dominica", "Fiji", "Ghana", "Grenada", "Guyana", "India", "Jamaica", "Kenya",
"Kiribati", "Lesotho", "Malawi", "Malaysia", "Maldives", "Malta", "Mauritius",
"Mozambique", "Namibia", "Nauru", "New Zealand", "Nigeria", "Pakistan", "Papua
New Guinea", "Rwanda", "St. Kitts and Nevis", "Saint Lucia", "St. Vin. and
Gren.", "Samoa", "Seychelles", "Sierra Leone", "Singapore", "Solomon Is.",
"South Africa", "Sri Lanka", "Swaziland", "Tanzania", "Tonga", "Trinidad and
Tobago", "Tuvalu", "Uganda", "United Kingdom", "Vanuatu", "Zamibia")
leaflet() %>% addTiles() %>%
addPolygons(data=subset(world, name %in% commonwealth), weight=2)