问题
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?
回答1:
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")))
回答2:
Use coordinates()
, like this:
library(maptools)
xx <- readShapePoints(system.file("shapes/baltim.shp", package="maptools")[1])
coordinates(xx)
# coords.x1 coords.x2
# 0 907.0 534.0
# 1 922.0 574.0
# 2 920.0 581.0
# 3 923.0 578.0
# 4 918.0 574.0
# [.......]
回答3:
st_coordinates
solve the problem, however it removes removes covariates linked to the coordinates from the sf object. here I share an alternative in case you need them:
# useful enough
sites_sf %>%
st_coordinates()
#> X Y
#> 1 -80.14401 26.47901
#> 2 -80.10900 26.83000
# alternative to keep covariates within a tibble/sf
sites_sf %>%
st_coordinates_tidy()
#> Joining, by = "rowname"
#> Simple feature collection with 2 features and 3 fields
#> geometry type: POINT
#> dimension: XY
#> bbox: xmin: -80.14401 ymin: 26.479 xmax: -80.109 ymax: 26.83
#> epsg (SRID): 4326
#> proj4string: +proj=longlat +datum=WGS84 +no_defs
#> # A tibble: 2 x 4
#> gpx_point X Y geometry
#> <chr> <dbl> <dbl> <POINT [°]>
#> 1 a -80.1 26.5 (-80.14401 26.47901)
#> 2 b -80.1 26.8 (-80.109 26.83)
- complete reprex: https://avallecam.github.io/avallecam/reference/st_coordinates_tidy.html
- source code: https://github.com/avallecam/avallecam/blob/master/R/spatially_useful.R
来源:https://stackoverflow.com/questions/16462290/obtaining-latitude-and-longitude-with-from-spatial-objects-in-r