Display SpatialPolygonsDataFrame on leaflet map with R

只谈情不闲聊 提交于 2019-12-18 12:34:36

问题


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. Many thanks in advance for your help!


回答1:


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)



来源:https://stackoverflow.com/questions/29118059/display-spatialpolygonsdataframe-on-leaflet-map-with-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!