[R-sig-Geo] Reading multiple layer/geometry KML into R

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Tue Oct 22 00:49:48 CEST 2013


On Mon, Oct 21, 2013 at 11:07 PM, Robin Edwards <geotheory1 at gmail.com> wrote:
> I'm vaguely aware there is an issue with reading KML files into R that have
> contain layers/geometries - e.g. as Barry describes in  this r-sig-geo post
> <http://r-sig-geo.2731867.n2.nabble.com/convert-KML-file-into-shape-file-or-CSV-file-td4136757.html>
> , listing one particular problem as arising when "the individual KMZ files
> which do contain the data have multiple layers".  Is there any way around
> this, or is it insurmountable with rgeos as it stands?
>
> A reproducible example:
>
> 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)
>
> yields errors in Windows & Mac:
>
> Windows: Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding,
> use_iconv = use_iconv) :
>   Cannot open layer
> OSX: Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding,
> use_iconv = use_iconv) :
>   Multiple incompatible geometries: 1:2

 The problem here is that the one layer has both points and line features.

 If you edit the KML with a text editor you'll see <point> tags and a
<linestring> tag. R's spatial classes can't handle data that mixes
points, lines, or polygons and so it fails.

 This one is quite easy to fix by hand - just cut out the one
linestring feature from the KML, and then you are left with just the
points. You can also use ogr2ogr on the command line to convert to a
shapefile, dropping the line features by using -skipfailures on the
line:

ogr2ogr -skipfailures -f "ESRI Shapefile"  shack.shp shackleton.kml

that writes a points-only shapefile called shack.shp/dbf/shx.

Given that KML is XML, you could also write some XML parser code to
read the KML and remove the non-point features, or convert the
linestrings or polygons to a centroid....

Barry



More information about the R-sig-Geo mailing list