Display SpatialPolygonsDataFrame on leaflet map with R

后端 未结 1 934
予麋鹿
予麋鹿 2020-12-30 14:20

I would like to display the polygon of Canada on a leaflet map.

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

I was able

相关标签:
1条回答
  • 2020-12-30 14:48

    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)
    

    enter image description here

    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)
    

    enter image description here

    0 讨论(0)
提交回复
热议问题