geotheory geotheory - 10 months ago 96
R Question

Reading KML files into R

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:

download.file("", "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)

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.


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

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

but this seems to yield nothing useful.

Answer Source

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..