如何使用r循环在传单地图中添加多个多边形? [英] How to add multiple polygons in leaflet map using r loop?

查看:61
本文介绍了如何使用r循环在传单地图中添加多个多边形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据一些国家/地区代码列表,我正在尝试向传单世界地图中添加多个多边形.我试图使用R循环添加多边形.这是我从列表1中手动添加多边形的代码:

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')

我正在考虑使用循环添加多个多边形图层,以便用于list_n:

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')

  }

问题是如何将循环嵌入到"leflet()%>%"?

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

*请注意此处:如果尝试在addPolygons()中添加多个数据,它将仅绘制数据中的第一个元素,在以下情况下,将仅绘制国家/地区"PAK":

*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')

推荐答案

以下是使用软件包 sf mapview 的解决方案.请注意,目前只有使用 mapview 的开发版本才能做到这一点(请参见注释掉的 devtools :: install_github()

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

请注意, addFeatures 是类型无关的,因此点,线和/或多边形的任意组合都可以在此处使用.

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

这篇关于如何使用r循环在传单地图中添加多个多边形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆