将纬度和经度转换为空间点,并将其投影到R中的另一张地图上

时间:2019-02-17 06:02:36

标签: r rgdal

我从官方政府站点下载了墨西哥及其所有州的SHP地图。我也有一个包含300个气象站及其坐标的数据集。 我想将这300个测站添加到SHP对象中。但是,我的坐标似乎不在同一地理空间区域。

我阅读并绘制了墨西哥地图。然后,我将所有300个测站的纬度和经度转换为空间点。不幸的是,当我将它们添加到地图上时,我无法发现它们。

这是我的代码:

# Read official SHP map
Mex <- readOGR(dsn = "/Desktop",
               layer = "areas_geoestadisticas_estatales")
# Turn `stations` into Spatial Points and project them onto `Mex`
Geo_stations <- SpatialPoints(stations[, c("stations_lat", "stations_long")],
                              proj4string = CRS(proj4string(mex)))
# Plot `Mex`, then add `Geo_stations`
plot(Mex) 
plot(Geo_stations, col = "red", add = TRUE) # Nowhere to be found

如果您想重复此练习,请you can download the map here

这是我的stations数据集的示例:

    station_number station_lat station_long
 1:          10003      25.100     -106.567
 2:          10018      24.944     -106.259
 3:          10031      24.523     -105.952
 4:          10038      23.554     -105.411
 5:          10042      24.174     -105.967
 6:           1004      22.001     -102.199
 7:          10050      25.063     -106.531
 8:           1005      21.781     -102.372
 9:          10064      24.148     -105.953
10:          10087      25.129     -106.363

比较coordinates(Mex)coordinates(Geo_stations)的结果后,我意识到Mex的“坐标”是巨大的数字,而来自站点的坐标则看起来像实际的地理空间参考。我想我没有正确将它们投影到Mex上。我希望plot(Geo_stations, add = TRUE)在全国各地添加一层电台。

1 个答案:

答案 0 :(得分:1)

library(sf)
library(mapview)

#load the shapefile
sh = st_read( "./702825217341_s/conjunto_de_datos/areas_geoestadisticas_estatales.shp",
              stringsAsFactors = FALSE )

#set encoding of second column, because of the special characters used
Encoding(sh$NOM_ENT) <- "UTF-16"
#set crs of the current map
st_set_crs( sh, 5332 )
#transform to WGS84-coordinates
st_transform( sh, 4326 )

#let's see what we have so far
mapview::mapview(sh)

enter image description here

看起来还可以。

现在,您可以将测站添加到一个sf对象中,然后将其绘制到地图中。

#sample stations
stations <- data.frame( station_number = c(10003),
                        station_alt = c(1754),
                        station_long = c(-106.567),
                        station_lat = c(26)
)

#make a sf-object out of them
stations <- st_as_sf( stations, coords = c( "station_long", "station_lat" ) )

#and plot
mapview::mapview( list( sh, stations ) )

enter image description here