2
votes

I'm trying to add multiple polygon to leaflet world map, according to a number of lists of country code. And I was trying to use R loop to add the polygon. Here's the code that I manually add polygons from list 1:

library(sp)
library(raster)
library(leaflet)
library(maps)
library(tidyverse)

countries_1 <- c('PAK','TUR','BGR')

adm1 <- getData('GADM', country='PAK', level=0)
adm2 <- getData('GADM', country= 'TUR', level=0)
adm3 <- getData('GADM', country= 'BGR', level=0)


leaflet() %>% 
  addTiles() %>% 
  addPolygons(data=adm1, weight = 3, fillColor = 'purple', color = 'purple') %>%
  addPolygons(data=adm2, weight = 3, fillColor = 'purple', color = 'purple') %>%
  addPolygons(data=adm3, weight = 3, fillColor = 'purple', color = 'purple')

I am thinking using the loop to add multiple polygon layers so that for list_n:

 countries_n <- ('ctry1','ctry2','ctry3',...'ctryn') 

 for (i in country_n) {

   countries <-  basemap %>% addPolygons(data=getData('GADM',country = i, level = 0),
  weight = 3, fillColor = 'purple', color = 'purple')

  }

The question is how can I embed the loop to "leflet() %>%" ?

*Note here: If try to add multiple data in addPolygons(), it will plot only the first element in the data, in below case, only country 'PAK' will be ploted:

addPolygons(data=c('PAK','TUR'), weight = 3, fillColor = 'purple', color = 'purple')
1
Can't you just merge the data and map country to a variable?Roman Luštrik
@RomanLuštrik please read the Note. If you merge them into a variable, it'll only plot the first element in the list.Daisywang
It looks like you are adding a base map every time you go through the loop, can you instead create countries in a loop pasted string of polygons then just pipe that to the end of your leaflet%>%addTiles%>%. You could just paste with the pipe command at the end of each iteration in it inside the loop....sconfluentus

1 Answers

7
votes

Here's a solution using packages sf and mapview. Note that this is currently only possible using the develop version of mapview (see commented out devtools::install_github()

# devtools::install_github("r-spatial/mapview@develop")
library(sf)
library(mapview)
library(raster)

countries_1 <- c('PAK','TUR','BGR')

dat_list = lapply(countries_1, function(i) {
  st_as_sf(getData("GADM", country = i, level = 0))
})

m = leaflet() %>% addTiles()

for (i in dat_list) {
  m = mapview::addFeatures(map = m, 
                           data = i, 
                           weight = 3, 
                           fillColor = 'purple', 
                           color = 'purple')
}

m

Note that addFeatures is type agnostic, so any combination of points, lines and/or polygons will work here.