Search code examples
rmap-projections

r - match spatial projections of spatial objects and overlay plots


I am trying to overlay 2 spatial objects using the plot() function. I understand that the projections of the 2 objects (of class SpatialLinesDataFrame and SpatialPolygonsDataFrame) need to be the same in order to have them visualized in the same plot. I've found similar questions here and here, but none of these can help me what I want to achieve.

Here's the coding for the SpatialPolygonsDataFrame. (v.map is a list of .kml files and loccoor is an object that stores location and corresponding x and y coordinates):

map.l<-list()

for (i in 1:length(v.map)){
  ll<-ogrListLayers(paste(loccoor,"/",v.map[i],".kml",sep=""))
  shp<-readOGR(paste(loccoor,"/",v.map[i],".kml",sep=""),layer=ll)
  map<-spTransform(shp, CRS("+proj=longlat +datum=WGS84"))
  map.l[[i]]<-map
}
plot(map.l[[1]],xlim=c(min(coor[,3]),max(coor[,3])),
     ylim=c(min(coor[,2]),max(coor[,2])))
for (i in 2:length(v.map)){
plot(map.l[[i]],xlim=c(min(coor[,3]),max(coor[,3])),
     ylim=c(min(coor[,2]),max(coor[,2])),add=T)
}

projection SpatialPolygonsDataFrame "map": "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"

projection SpatialLinesDataFrame "contours": "+proj=aeqd +ellps=WGS84 +lon_0=-XX.XXXXX +lat_0=XX.XXXXX".

I want to transform the projection of the "map" object to match that of the "contours". Simply replacing the "CRS("+proj=longlat +datum=WGS84")" of the "map" object with the projection of the "contours" object doesn't seem to work, because then the polygons are no longer plotted (visible).

Any thoughts to this would be greatly appreciated!


Solution

  • Here's a not very great metaphor: The coordinates are like directions, and the crs tells us what language the directions are in. So, if you change the crs, but you leave the coordinates as they are, then it would be like trying to read German directions with a Spanish dictionary.

    We can translate the directions from one crs to another using sp::spTransform(). The function takes two arguments: a spatial object, and a crs.

    We can use raster::crs() to get the crs from the another spatial object. So, to transform the map's coordinates (and crs) to the crs of the contours:

    map <- spTransform(map, crs(contours))