R传单:如何使用leaflet :: addPolygons()显示“合并的” SpatialPolygonsDataFrame?

时间:2018-12-15 09:37:23

标签: r leaflet polygon

我了解如何操作SpatialPolygonsDataFrame类的对象,并且可以使用base R或传单在地图上显示它们。

但是我不明白为什么下面的代码段不再适用于“合并”的多边形。我正在使用rmapshaper::ms_dissolve()来组合多边形,这不会改变对象类...

您能帮助找出错误吗?提前非常感谢您!

我在下面提供了一个最小的可复制示例。第1部分和第2部分可以。第三部分休息。.

# Load required packages
library(dplyr)           
library(leaflet)         
library(rmapshaper) 

# load data (example dataset from leaflet)
test_data <- gadmCHE
# inspect class (SpatialPolygonsDataFrame)
test_data %>% class()

# ---------------------- #
# FIRST PART WORKS FINE  #
# - add colors           #
# - display using base R #
# - disply using leaflet #
# ---------------------- #

# add color to test_data (red)
test_data@data <- test_data@data %>% mutate(color = "#ff0000")
# basic plot (works fine)
plot(test_data, col = test_data@data$color)
# leaflet plot (works fine)
leaflet() %>% 
  addTiles() %>% 
  addPolygons(data = test_data, color = test_data@data$color)
# change color of particular regions (yellow)
test_data@data <- test_data@data %>% 
  mutate(GROUP = ifelse(OBJECTID <= 5 | OBJECTID %in% c(16,25), 99, OBJECTID),
         color = ifelse(GROUP == 99, "#ffff00", color))
# basic plot (works fine)
plot(test_data, col = test_data@data$color)
# leaflet plot (works fine)
leaflet() %>% 
  addTiles() %>% 
  addPolygons(data = test_data, color = test_data@data$color)

# ---------------------- #
# 2ND PART WORKS FINE    #
# - merge                #
# - display using base R #
# ---------------------- #

# split polygons (works fine)
temp_1 <- test_data[test_data@data$GROUP == 99,]
temp_2 <- test_data[test_data@data$GROUP != 99,]

# merge (works fine)
new_group <- ms_dissolve(temp_1, copy_fields = colnames(test_data@data))
# basic plot (works fine)
plot(new_group, col = new_group@data$color)

# ----------------------- #
# LAST PART DOES NOT WORK #
# - display using leaflet #
# ----------------------- #

# leaflet plot (DOES NOT WORK)
leaflet() %>% 
  addTiles() %>% 
  addPolygons(data = temp_2, color = temp_2@data$color)
  addPolygons(data = new_group, color = new_group@data$color)

# => HOW TO MAKE NEW_GROUP APPEAR IN YELLOW ON THE LEAFLET MAP?

0 个答案:

没有答案