Search code examples
rgdalrgdal

Obtaining Latitude and Longitude with from Spatial objects in R


I want to obtain the latitude and longitude from a shapefile. Until now, I only know how to read the shapefile.

library(rgdal)
centroids.mp <- readOGR(".","35DSE250GC_SIR")

But how I can extract the latitude and longitude from centroids.mp?


Solution

  • There's a few levels to this question.

    You ask for longitude and latitude, but that may not be the coordinate system used by this object. You can get the coordinates like this

       coordinates(centroids.mp)
    

    Note that the "centroids" will be all of the coordinates if this is a SpatialPointsDataFrame, a list of all the line coordinates if this is a SpatialLinesDataFrame, and just the centroids if this is a SpatialPolygonsDataFrame.

    The coordinates may be longitude and latitude, but the object may not know that. Use

       proj4string(centroids.mp) 
    

    If that is "NA", then the object does not know (A). If it includes "+proj=longlat", the object does know and they are longitude/latitude (B). If it includes "+proj=" and some other name (not "longlat") then the object does know and it's not longitude/latitude (C).

    If (A) you'll have to find out, or it might be obvious from the values.

    If (B) you are done (though you should check assumptions first, these metadata can be incorrect).

    If (C) you can (pretty reliably though you should check assumptions first) transform to longitude latitude (on datum WGS84) like this:

     coordinates(spTransform(centroids.mp, CRS("+proj=longlat +datum=WGS84")))