I am adding two circles and a polygon to a leaflet map. Here\'s my code which plots these three shapes. Is there any way I can get a union of these three shapes?
I'd recommend moving away from spatial objects from the sp
package and instead look at simple feature objects from the sf package.
Simple Features are the 'new' spatial class for R (and are made by the same guy who did sp
).
So, to get the union of your circles, you can use
library(rgeos)
library(sf)
## A dataframe of your points
df <- data.frame(lon = c(ptTop1[1], ptTop2[1], ptBottom1[1], ptBottom2[1]),
lat = c(ptTop1[2], ptTop2[2], ptBottom1[2], ptBottom2[2]))
## convert them into a simple features data.frame
sf_df <- st_as_sf(df, coords = c("lon", "lat"))
## convert into circles
sf_circles <- st_buffer(sf_df, dist = 0.04)
## find the union of all the circles
sf_combined <- st_union(sf_circles)
## now sf_combined is a single polygon
sf_combined
# Geometry set for 1 feature
# geometry type: POLYGON
# dimension: XY
# bbox: xmin: 72.79573 ymin: 20.38366 xmax: 72.88561 ymax: 20.47837
# epsg (SRID): NA
# proj4string: NA
# POLYGON((72.8745460445306 20.4072956786729, 72....
As for plotting, leaflet can handle sf
objects (except for MULTIPOINT), so you can plot it directly
library(leaflet)
sp <- as(sf_combined, 'Spatial')
sf_combined %>%
leaflet() %>%
addTiles() %>%
addPolygons()