How to add a hole to a polygon within a SpatialPolygonsDataFrame?

拈花ヽ惹草 提交于 2020-01-10 05:29:06

问题


I have a list of polygons in a SpatialPolygonsDataFrame and need to set one of them as a hole in an other.

I've found in the help of set_Polypath how a hole can be defined on a newly created polygon but how to set the "hole" flag on an existing polygon?


回答1:


It looks like you have to rebuild the polygon, and then replace it in the spdf.

The following function automatically rebuild the polygon adding a hole:

library("sp")
AddHoleToPolygon <-function(poly,hole){
    # invert the coordinates for Polygons to flag it as a hole
    coordsHole <-  hole@polygons[[1]]@Polygons[[1]]@coords
    newHole <- Polygon(coordsHole,hole=TRUE)

    # punch the hole in the main poly
    listPol <- poly@polygons[[1]]@Polygons
    listPol[[length(listPol)+1]] <- newHole
    punch <- Polygons(listPol,poly@polygons[[1]]@ID)

    # make the polygon a SpatialPolygonsDataFrame as the entry
    new <- SpatialPolygons(list(punch),proj4string=poly@proj4string)
    new <- SpatialPolygonsDataFrame(new,data=as(poly,"data.frame"))

    return(new)
}

You can then then define a polygon with a whole from two polygons in a SpatialPolygonsDataFrame:

load(url("http://spatcontrol.net/CorentinMBarbu/misc/spdf.rda"))
punchedPoly <-AddHoleToPolygon(spdf[1,],spdf[2,])

And get:

And then replace the polygon in the spdf

spdf <- rbind(punchedPoly,spdf[2,])
plot(spdf,col=c(1,2),main="New SpatialPolygonsDataFrames")



来源:https://stackoverflow.com/questions/29624895/how-to-add-a-hole-to-a-polygon-within-a-spatialpolygonsdataframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!