# LIBKML Driver (.kml .kmz)

The LIBKML driver is a client of Libkml from Google, a reference implementation of KML reading and writing, in the form of a cross platform C++ library. You must build and install Libkml in order to use this OGR driver. Note: you need to build libkml from its latest SVN version (libkml 1.2 isn't enough).

Note that if you build and include this LIBKML driver, it will become the default reader of KML for ogr, overriding the previous KML driver. You can still specify either KML or LIBKML as the ouput driver via the command line

Libkml from Google provides reading services for any valid KML file. However, please be advised that some KML facilities do not map into the Simple Features specification ogr uses as its internal structure. Therefore, a best effort will be made by the driver to understand the content of a KML file read by libkml into ogr, but your mileage may vary. Please try a few KML files as samples to get a sense of what is understood. In particular, nesting of feature sets more than one deep will be flattened to support ogr's internal format.

## Datasource

You may specify a datasource as a kml file `somefile.kml` , a directory `somedir/` , or a kmz file `somefile.kmz` .

By default on directory and kmz datasources, an index file of all the layers will be read from or written to doc.kml. It conatains a <NetworkLink> to each layer file in the datasource. This feature can be turned off by setting the enviroment variable LIBKML_USE_DOC.KML to "no"

### StyleTable

Datasource style tables are written to the <Document> in a .kml, style/style.kml in a kmz file, or style.kml in a directory, as one or more <Style> elements. Not all of OGR Feature Style can translate into KML.

## Layer

Layers are mapped to kml files as a <Document> or <Folder>, and in kmz files or directorys as a seperate kml file.

### Style

Layer style tables can not be read from or written to a kml layer that is a <Folder>, otherwise they are in the <Document> that is the layer.

### Schema

Read and write of <Schema> is supported for .kml files , .kmz files, and directorys.

## Feature

An OGR feature translates to kml as a <Placemark>, and vice-versa.

Starting with OGR 1.10, KML <GroundOverlay> elements are supported for reading (unless the LIBKML_READ_GROUND_OVERLAY configuration option is set to FALSE). For such elements, there are icon and drawOrder fields.

### Style

Style Strings at the feature level are Mapped to KML as either a <Style> or <StyleUrl> in each <Placemark>.

When reading a kml feature and the enviroment variable LIBKML_RESOLVE_STYLE is set to yes, styleurls are looked up in the style tables and the features style string is set to the style from the table. This is to allow reading of shared styles by applications, like mapserver, that do not read style tables.

When reading a kml feature and the enviroment variable LIBKML_EXTERNAL_STYLE is set to yes, a styleurl that is external to the datasource is read from disk or fetched from the server and parsed into the datasource style table. If the style kml can not be read or LIBKML_EXTERNAL_STYLE is set to no then the styleurl is copyed to the style string.

When reading a kml StyleMap the default mapping is set to normal. If you wish to use the highlighted styles set the enviroment variable LIBKML_STYLEMAP_KEY to "highlight"

## Fields

OGR fields (feature atributes) are mapped to kml with <Schema>; and <SimpleData>, except for some special fields as noted below.

A rich set of environment variables are available to define how fields in input and output, map to a KML <Placemark>. For example, if you want a field called 'Cities' to map to the <name>; tag in KML, you can set an environment variable.

Name
  This String field maps to the kml tag <name>. The name of the ogr field can be changed with the enviroment variable LIBKML_NAME_FIELD .
description
  This String field maps to the kml tag <description>. The name of the ogr field can be changed with the enviroment variable LIBKML_DESCRIPTION_FIELD .
timestamp
  This string or datetime or date and/or time field maps to the kml tag <timestamp>. The name of the ogr field can be changed with the enviroment variable LIBKML_TIMESTAMP_FIELD .
begin
  This string or datetime or date and/or time field maps to the kml tag <begin>. The name of the ogr field can be changed with the enviroment variable LIBKML_BEGIN_FIELD .
end
  This string or datetime or date and/or time field maps to the kml tag <end>. The name of the ogr field can be changed with the enviroment variable LIBKML_END_FIELD .
altitudeMode
  This string field maps to the kml tag <altitudeMode> or <gx:altitudeMode>. The name of the ogr field can be changed with the enviroment variable LIBKML_ALTITUDEMODE_FIELD .
tessellate
  This integer field maps to the kml tag <tessellate>. The name of the ogr field can be changed with the enviroment variable LIBKML_TESSELLATE_FIELD .
extrude
  This integer field maps to the kml tag <extrude>. The name of the ogr field can be changed with the enviroment variable LIBKML_EXTRUDE_FIELD .
visibility
  This integer field maps to the kml tag <visibility>. The name of the ogr field can be changed with the enviroment variable LIBKML_VISIBILITY_FIELD .
icon
  This string field maps to the kml tag <icon>. The name of the ogr field can be changed with the enviroment variable LIBKML_ICON_FIELD .
drawOrder
  This integer field maps to the kml tag <drawOrder>. The name of the ogr field can be changed with the enviroment variable LIBKML_DRAWORDER_FIELD .
OGR_STYLE
  This string field maps to a features style string, OGR reads this field if there is no style string set on the feature.

## Geometry

Translation of OGR Geometry to KML Geometry is pretty strait forwards with only a couple of exceptions. Point to <Point>, LineString to <LineString>, LinearRing to <LinearRing>, and Polygon to <Polygon>. In OGR a polygon contains an array of LinearRings, the first one being the outer ring. KML has the tags <outerBoundaryIs> and <innerBoundaryIs> to differentiate between the two. OGR has several Multi types of geometry : GeometryCollection, MultiPolygon, MultiPoint, and MultiLineString. When possible, OGR will try to map <MultiGeometry> to the more precise OGR geometry type (MultiPoint, MultiLineString or MultiPolygon), and default to GeometryCollection in case of mixed content.

Sometimes kml geometry will span the dateline, In applications like qgis or mapserver this will create horizontal lines all the way around the globe. Setting the enviroment variable LIBKML_WRAPDATELINE to "yes" will cause the libkml driver to split the geometry at the dateline when read.

## VSI Virtual File System API support

(Some features below might require OGR >= 1.9.0)

The driver supports reading and writing to files managed by VSI Virtual File System API, which include "regular" files, as well as files in the /vsizip/ (read-write) , /vsigzip/ (read-write) , /vsicurl/ (read-only) domains.

Writing to /dev/stdout or /vsistdout/ is also supported.

## Example

The following bash script will build a csv file and a vrt file, and then translate them to KML using ogr2ogr into a .kml file with timestamps and styling.

    #!/bin/bash
    # Copyright (c) 2010, Brian Case
    #
    # Permission is hereby granted, free of charge, to any person obtaining a
    # copy of this software and associated documentation files (the "Software"),
    # to deal in the Software without restriction, including without limitation
    # the rights to use, copy, modify, merge, publish, distribute, sublicense,
    # and/or sell copies of the Software, and to permit persons to whom the
    # Software is furnished to do so, subject to the following conditions:
    #
    # The above copyright notice and this permission notice shall be included
    # in all copies or substantial portions of the Software.
    #
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
    # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    # DEALINGS IN THE SOFTWARE.

    icon="http://maps.google.com/mapfiles/kml/shapes/shaded_dot.png"
    rgba33="#FF9900"
    rgba70="#FFFF00"
    rgba150="#00FF00"
    rgba300="#0000FF"
    rgba500="#9900FF"
    rgba800="#FF0000"

    function docsv {

        IFS=','

        while read Date Time Lat Lon Mag Dep
        do
            ts=$(echo $Date | sed 's:/:-:g')T${Time%%.*}Z
            rgba=""

            if [[ $rgba == "" ]] && [[ $Dep -lt 33 ]]
            then
                rgba=$rgba33
            fi

            if [[ $rgba == "" ]] && [[ $Dep -lt 70 ]]
            then
                rgba=$rgba70
            fi

            if [[ $rgba == "" ]] && [[ $Dep -lt 150 ]]
            then
                rgba=$rgba150
            fi

            if [[ $rgba == "" ]] && [[ $Dep -lt 300 ]]
            then
                rgba=$rgba300
            fi

            if [[ $rgba == "" ]] && [[ $Dep -lt 500 ]]
            then
                rgba=$rgba500
            fi

            if [[ $rgba == "" ]]
            then
                rgba=$rgba800
            fi

            style="\"SYMBOL(s:$Mag,id:\"\"$icon\"\",c:$rgba)\""

            echo $Date,$Time,$Lat,$Lon,$Mag,$Dep,$ts,"$style"
        done

    }

    wget http://neic.usgs.gov/neis/gis/qed.asc -O /dev/stdout |\
     tail -n +2 > qed.asc

    echo Date,TimeUTC,Latitude,Longitude,Magnitude,Depth,timestamp,OGR_STYLE > qed.csv

    docsv < qed.asc >> qed.csv

    cat > qed.vrt << EOF
    <OGRVRTDataSource>
        <OGRVRTLayer name="qed">
            <SrcDataSource>qed.csv</SrcDataSource>
            <GeometryType>wkbPoint</GeometryType>
            <LayerSRS>WGS84</LayerSRS>
            <GeometryField encoding="PointFromColumns" x="Longitude" y="Latitude"/>
        </OGRVRTLayer>
    </OGRVRTDataSource>

    EOF

    ogr2ogr -f libkml qed.kml qed.vrt