使用R在Leaflet地图上显示SpatialPolygonsDataFrame

时间:2015-03-18 09:19:05

标签: r leaflet polygon

我想在传单地图上显示加拿大的多边形。

# create map
library(leaflet)
m = leaflet() %>% addTiles()
m

我能够找到加拿大的多边形:http://www.gadm.org/country。 我为R选择了SpatialPolygonsDataFrame格式,但还有其他格式可用(例如Shapefile)

# load object in R
load("country_polygons/CAN_adm0.RData")
pol_can <- gadm

如何在地图上显示形状?我假设我必须利用sp包,但我无法弄清楚如何这样做。 非常感谢您的帮助!

1 个答案:

答案 0 :(得分:15)

您可以按照文档here的第2.2节将SpatialPolygons*对象传递给addPolygons函数。

例如(请注意,以下内容包括~11.4 MB下载):

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)

enter image description here

请注意,也可以使用getData包中的raster函数下载GADM数据:

library(raster)
can <- getData('GADM', country='VAT', level=0)

修改

在回复评论时,我非常喜欢Natural Earth提供的轻量级多边形数据集。这是一个例子,我从自然地球下载1:50,000,000个国家的shapefile(Admin 0),将其分配给英联邦的现有成员,并绘制这些。压缩的shapefile小于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)

enter image description here