如何使用 st_read 从 kml 文件获取 R 中的坐标

How to get coordinates in R from kml file using st_read

我正在使用 r,我正在尝试从 KML 文件中获取地理坐标(纬度和经度)。我正在使用我在 Google Earth 中创建的 KML 文件,我在下一个代码中使用 sf package 中的 st_read() 以正确的方式获取坐标:

Google_earth_kml <- st_read("prueba_direcciones_google_earth.kml")

问题是我得到下一个 table:

Name                                                         description                             Geometry
store 1                   address: Barros Luco 2058<br>RUT: 08.180.861-9          c(-71.6132, -33.5985683, 0)
store 2   address: AVENIDA DOMINGO SANTA MARIA 1789<br>RUT: 76.585.397-4       c(-70.6639313, -33.4155609, 0)

我想要 table 喜欢:

Name                             address          Rut        long         lat
store 1                 Barros Luco 2058 08.180.861-9    -71.6132 -33.5985683
store 2 AVENIDA DOMINGO SANTA MARIA 1789 76.585.397-4 -70.6639313 -33.4155609

这只是我数据的一小部分。我知道您可能需要 KML 文件,但出于政治和隐私的原因,我无法共享它。

不知道有没有人可以给我意见或者其他观点。 任何帮助将不胜感激。

为此我们可以使用 st_coordinates()

关于数据,我刚刚在网上找到了一个带有点几何图形的示例 KML 文件。我建议您在拥有以后无法共享的数据时尝试这样做。

数据

library(sf)
library(dplyr)

sample_KML <- "https://github.com/mapbox/Simple-KML/raw/master/sample/example.kml"

KML_sf <- st_read(sample_KML) %>% 
  slice(1:4) # keep only the first 4 rows. The 5th row is a polygon

KML_sf

Simple feature collection with 4 features and 2 fields
geometry type:  POINT
dimension:      XYZ
bbox:           xmin: -122.6819 ymin: -22.90833 xmax: 28.97602 ymax: 64.13333
z_range:        zmin: 0 zmax: 0
CRS:            4326
            Name Description                       geometry
1       Portland                POINT Z (-122.6819 45.52 0)
2 Rio de Janeiro             POINT Z (-43.19639 -22.9083...
3       Istanbul              POINT Z (28.97602 41.01224 0)
4      Reykjavik             POINT Z (-21.93333 64.13333 0)

输出

output <- KML_sf %>% 
  mutate(long = st_coordinates(.)[,1],
         lat = st_coordinates(.)[,2])


output

Simple feature collection with 4 features and 4 fields
geometry type:  POINT
dimension:      XYZ
bbox:           xmin: -122.6819 ymin: -22.90833 xmax: 28.97602 ymax: 64.13333
z_range:        zmin: 0 zmax: 0
CRS:            4326
            Name Description                       geometry       long       lat
1       Portland                POINT Z (-122.6819 45.52 0) -122.68194  45.52000
2 Rio de Janeiro             POINT Z (-43.19639 -22.9083...  -43.19639 -22.90833
3       Istanbul              POINT Z (28.97602 41.01224 0)   28.97602  41.01224
4      Reykjavik             POINT Z (-21.93333 64.13333 0)  -21.93333  64.13333

如果您想删除几何列:

output %>% st_drop_geometry()

            Name Description       long       lat
1       Portland             -122.68194  45.52000
2 Rio de Janeiro              -43.19639 -22.90833
3       Istanbul               28.97602  41.01224
4      Reykjavik              -21.93333  64.13333