[R-sig-Geo] convert KML file into shape file or CSV file

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Wed Dec 9 14:32:40 CET 2009


On Wed, Dec 9, 2009 at 1:22 AM, rusers.sh <rusers.sh at gmail.com> wrote:
> Hi all,
>  Does anybody know how to import a KML file in R and them save it as a
> shape or CSV file. Take the following KML file as an example,
> http://www.nature.com/nature/googleearth/avianflu1.kml
>  I have tried several extentions of
> ARCGIS,e.g.KML2Shape,KMLCSVConverter,KMLCSVConverter and XToolsPro, but
> unfortunately failed to do that. I didnot find a method to solve it in R.
>  If this cannot be done in R, i'd like to see your alternative method to do
> that.
>  Any help or suggestions are greatly appreciated.
>

 As well as the validation problems reported by Alex Mandel, the
structure of this KML file isn't appropriate for straight conversion
to a shape or CSV file.

 It has several parts, some "NetworkLink" structures without URLs that
just provide some HTML info boxes, and some network link structures
that point to other kmz files. You can download these kmz files, unzip
them, and possibly convert them to other formats. For example, one of
the links is to:

http://www.declanbutler.info/Flumaps1/4_Human_cases/Maps_of_human_cases_by
period/Cases_by_period1.kmz

which when unzipped produces doc.kml and some png files for markers.
ogrinfo tells us:

$ ogrinfo doc.kml
Had to open data source read-only.
INFO: Open of `doc.kml'
      using driver `KML' successful.
1: Data (3D Point)
2: Data (3D Point)
3: Data (3D Point)
4: Data (3D Point)
5: Data (3D Point)
6: Data (3D Point)
7: Data (3D Point)
8: Data (3D Point)

 - which is a bit weird, 8 layers all called 'Data'. That makes it
hard to extract individual layers by name. So I edited the file and
renamed them Data to Data8....

 I can then read them in R:

> data2=readOGR("doc.kml","Data2")
> plot(data2)

 I can then use writeOGR to create shapefiles, but it's easier on the
command line:

$ mkdir shapefile
$ ogr2ogr -f "ESRI Shapefile" shapefile doc.kml

So there's umpteen things going on here, above and beyond any possible
structural problems with the KML in the first place:

1. The original KML file points to a bunch of KMZ files, and readOGR
isn't going to do all that work for you.
2. Even if it could do all that work, the KML is a complex structure
with all sorts of geographic and no-geographic entities and so it
can't bung it all into a simple shapefile
3. The individual KMZ files which do contain the data have multiple layers.
4. The layers within a KMZ file (or at least, the one I bothered to
look at) have identical names which breaks stuff.

Otherwise, it's easy! :)

Barry



More information about the R-sig-Geo mailing list