I want to determine which points from a set of hundreds of geographic coordinates are located into a shape polygon. I was able to convert all the coordinates (latitude and longitude ) into a SpatialPointsDataFrame and I can read and plot the shapefile in R as well. A graph of my shp file together with the points is:
From similar questions I was trying to use the function point.in.polygon in the sp package as well as the the over() function.
Polygon: polygon1,
Points: spdf
pt.in.poly <- sp::over( spdf, polygon1, fn = NULL)
or:
new_shape <- point.in.poly(spdf, polygon1)
but in both cases the result I get is:
Error: identicalCRS(x, y) is not TRUE
The SpatialPointsDataFrame was created with the coordinates: CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0") and the shapefile have the CRS arguments: +proj=cea +lon_0=0 +lat_ts=30 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0 , so they seem to be the same, I am not sure, Im not an expert on this.
If its a problem of coordinates system how can I fix it? or what am I doing wrong?
Best Answer
You have to transform your polygon (shapefile) Coordinate Reference System (CRS) with the function
spTransform
from thesp
package. You can simply do this:I also give you a complete reproducible example below:
Get example data:
Plot data:
Spatial Query: points in polygon with different CRS:
Spatial Query: points in polygon with same CRS: