Reputation: 307
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')
Upvotes: 2
Views: 6783
Reputation: 5834
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.
Upvotes: 8