Reputation: 3854
I'm trying to get the coordinates of a set of points defining a grid within a polygon (which I have a shapefile for). It seemed like the simplest thing to do would be to create a grid of points, and then filter those points down to only the ones within the polygon. I looked at https://gis.stackexchange.com/questions/133625/checking-if-points-fall-within-polygon-shapefile and Convert a shapefile from polygons to points?, and based on the answers there I tried this:
library(rgdal)
city_bdry <- readOGR("Boundaries - City",
"geo_export_32ded882-2eab-4eaa-b9da-a18889600a40")
res <- 0.01
bb <- bbox(city_bdry)
gt <- GridTopology(cellcentre.offset = bb[,1], cellsize = c(res, res),
cells.dim = c(diff(bb[,1]), diff(bb[2,])) / res + 1)
pts <- SpatialPoints(gt, proj4string = CRS(proj4string(city_bdry)))
ov <- over(pts, city_bdry)
The result, however, doesn't include the actual coordinates of the points that overlap the polygon, so it's useless to me. How can I get that information to be included in the dataframe? Or, is there a simpler way to do what I'm trying to do?
The shapefile I'm using can be downloaded from https://data.cityofchicago.org/Facilities-Geographic-Boundaries/Boundaries-City/ewy2-6yfk
Upvotes: 3
Views: 1567
Reputation: 10350
You can also achieve this by simply subsetting the data with [
like yourPoints[yourPolygons, ]
:
library(raster)
bra <- getData(country = "BRA", level = 1)
pts <- makegrid(bra, 100)
pts <- SpatialPoints(pts, proj4string = CRS(proj4string(bra)))
coordinates(pts[bra, ])
Upvotes: 1
Reputation: 8412
Use splancs::inout()
.
1. Get the outline of your polygon
outline <- mySpatialPolygonsDataFrame@polygons[[2]]@Polygons[[1]]@coords
2. Use inout() to find what points are within the outline
library(splancs)
pts_in_polygon <- points[inout(points,outline), ]
Upvotes: 2
Reputation: 54247
If I got you right, you could try
library(rgdal)
download.file("https://data.cityofchicago.org/api/geospatial/ewy2-6yfk?method=export&format=Shapefile", tf<-tempfile(fileext = ".zip"), mode="wb")
unzip(tf, exdir=dir<-file.path(tempdir(), "Boundaries - City"))
city_bdry <- readOGR(dir, tools::file_path_sans_ext((list.files(dir)[1])))
res <- 0.01
bb <- bbox(city_bdry)
gt <- GridTopology(cellcentre.offset = bb[,1], cellsize = c(res, res),
cells.dim = c(diff(bb[,1]), diff(bb[2,])) / res + 1)
pts <- SpatialPoints(gt, proj4string = CRS(proj4string(city_bdry)))
ov <- sp::over(pts, as(city_bdry, "SpatialPolygons"))
pts_over <- pts[!is.na(ov)]
plot(city_bdry)
points(pts_over)
coordinates(pts_over)
Upvotes: 3