Reading KML files into R

2019-02-19 01:39发布

I'm building a workflow for reading multiple-geometry KML files into R. This is my working map, with point and path geometries. The (reproducible) R script is:

library(rgdal)
setwd( {SPECIFY A FOLDER} )
download.file("http://www.scribblemaps.com/maps/kml/shackleton.kml", "file.kml")
(lyr = ogrListLayers("file.kml"))
map = readOGR ("file.kml", layer=lyr, verbose = TRUE, drop_unsupported_fields=T, dropNULLGeometries=T)

which fails with:

Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv) : 
  Cannot open layer

Any ideas how to work around this?

I've managed to get the path data in by creating a new KML of just the path entry: in Google Earth click on the path entry in the kml object list, select 'copy', paste into text editor and save as KML. This opens in R with:

(lyr = ogrListLayers("path.kml"))
pathkml = readOGR ("path.kml", layer=lyr, verbose = TRUE, drop_unsupported_fields=T, dropNULLGeometries=T)
coordinates(pathkml)

But I've not achieved a workflow for the point data, which includes point labels and annotation. The preferable solution would read the original KML and negate the need for Google Earth, but of course whatever works.. Very grateful for assistance.


Appendum:

I'm now looking at using XML to parse this. The data seems structured within tags. I've got to:

require(XML)
d = xmlParse("shackleton.kml")
doc = xpathSApply(d, "//Placemark")

but this seems to yield nothing useful.

2条回答
迷人小祖宗
2楼-- · 2019-02-19 02:27

This R function should extract Placemark information (name, description and Point coordinates) from KML exported from Google Maps.

It works fine for the two maps I have at hand and supports NA values in names and descriptions (which explains why the internal get_field function is coded how it is).

Improvements very welcome.

Add. I have added a function to deal with Polygons. The code now allows you to plot KML Points and Polygons as in

ggplot(kml_points(map),
       aes(x = longitude, y = latitude)) +
  geom_polygon(data = kml_polygons(map), fill = "red", alpha = 0.5) +
  geom_point()

where map holds the path to a KML file.

WARNING: no support for multi-geometries (e.g. multi-polygons with holes).

查看更多
别忘想泡老子
3楼-- · 2019-02-19 02:31

This R-sig-geo thread also refers. It seems the only way to approach this would be to write a custom function to parse the KML as XML and build individual spatialPoints and spatialPolygons objects from the respective geometries. On balance probably more effective to just try and stick to single geometry KMLs..

查看更多
登录 后发表回答