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.
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 internalget_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
where
map
holds the path to a KML file.WARNING: no support for multi-geometries (e.g. multi-polygons with holes).
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..