LIBKML Driver (.kml .kmz)
Driver short name
LIBKML
Build dependencies
libkml
The LIBKML driver is a client of Libkml , 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 1.3 or master.
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 output 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.
Driver capabilities
Supports Create()
This driver supports the GDALDriver::Create()
operation
Supports Georeferencing
This driver supports georeferencing
Supports VirtualIO
This driver supports virtual I/O operations (/vsimem/, etc.)
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 contains a
<NetworkLink>
to each layer file in the datasource. This feature can be turned off by
setting the configuration option LIBKML_USE_DOC.KML
to "NO":
LIBKML_USE_DOC.KML=[YES/NO]: Defaults to
YES
. Use adoc.kml
index file.
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 Feature Style Specification can translate into KML.
Dataset creation options
Dataset creation options can be specified in command-line tools using the syntax -dsco <NAME>=<VALUE>
or by providing the appropriate arguments to GDALCreate()
(C) or Driver.Create
(Python).
The following dataset creation options can be
used to generate a
<atom:Author>
element at the top Document level.
AUTHOR_NAME=value: Specifieds the value of the
<atom:name>
element.AUTHOR_URI=value: Specifieds the value of the
<atom:uri>
element. It should start withhttp://
orhttps://
AUTHOR_EMAIL=value: Specifieds the value of the
<atom:email>
element. It should include a@
character.
Additional dataset creation options affecting the top Document level:
LINK=value: Specifies the href of an <atom:link> element at the top Document level.
PHONENUMBER=value: Specifies the value of the <phoneNumber> element at the top Document level. The value must follow the syntax of IETF RFC 3966.
DOCUMENT_ID=value: Defaults to
root_doc
. Specifies the id of the root <Document> node.
Container properties
The following dataset creation options can be used to set container options :
NAME=value: <name> element
VISIBILITY=value: <visibility> element
OPEN=value: <open> element
SNIPPET=value: <snippet> element
DESCRIPTION=value: <description> element
List style
The following dataset creation options can be used to control how the main folder (folder of layers) appear in the Places panel of the Earth browser, trough a <ListStyle> element:
LISTSTYLE_TYPE=[check/radioFolder/checkOffOnly/checkHideChildren]: Sets the <listItemType> element.
LISTSTYLE_ICON_HREF=value: URL of the icon to display for the main folder. Sets the href element of the <ItemIcon> element.
Balloon style
If a style foo is defined, it is possible to add a <BalloonStyle> element to it, by specifying the foo_BALLOONSTYLE_BGCOLOR and/or foo_BALLOONSTYLE_TEXT elements.
NetworkLinkControl
A <NetworkLinkControl> element can be defined if at least one of the following dataset creation option is specified:
NLC_MINREFRESHPERIOD=value: to set the <minRefreshPeriod> element
NLC_MAXSESSIONLENGTH=value: to set the <maxSessionLength> element
NLC_COOKIE=value: to set the <cookie> element
NLC_MESSAGE=value: to set the <message> element
NLC_LINKNAME=value: to set the <linkName> element
NLC_LINKDESCRIPTION=value: to set the <linkDescription> element
NLC_LINKSNIPPET=value: to set the <linkSnippet> element
NLC_EXPIRES=value: to set the <expires> element
Update documents
When defining the dataset creation option UPDATE_TARGETHREF, a NetworkLinkControl KML file with an <Update> element will be generated. See the tutorial about update.
The CreateFeature() operation on a layer will be translated as a <Create> element.
The SetFeature() operation on a layer will be translated as a <Change> element.
The DeleteFeature() operation on a layer will be translated as a <Delete> element.
Layer
OGRLayer
are mapped
to kml files as a
<Document>
or
<Folder>,
and in kmz files or directories as a separate 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 directories.
Layer creation options
Layer creation options can be specified in command-line tools using the syntax -lco <NAME>=<VALUE>
or by providing the appropriate arguments to GDALDatasetCreateLayer()
(C) or Dataset.CreateLayer
(Python).
The following layer creation options can be used
to generate a
<LookAt>
element at the layer level.
LOOKAT_LONGITUDE=value: (required)
LOOKAT_LATITUDE=value: (required)
LOOKAT_RANGE=value: (required)
LOOKAT_HEADING=value:
LOOKAT_TILT=value:
LOOKAT_ALTITUDE=value:
LOOKAT_ALTITUDEMODE=value:
Alternatively, a <Camera> element can be generated.
CAMERA_LONGITUDE=value: (required)
CAMERA_LATITUDE=value: (required)
CAMERA_ALTITUDE=value: (required)
CAMERA_ALTITUDEMODE=value: (required)
CAMERA_HEADING=value:
CAMERA_TILT=value:
CAMERA_ROLL=value:
A
<Region>
element can be generated to control when objects of the layer are
visible or not. If REGION_XMIN
, REGION_YMIN
, REGION_XMAX
and
REGION_YMAX
, the region coordinates are determined from the spatial
extent of the features being written in the layer.
ADD_REGION=[YES/NO]: Defaults to
NO
.REGION_XMIN=value: defines the west coordinate of the region.
REGION_YMIN=value: defines the south coordinate of the region.
REGION_XMAX=value: defines the east coordinate of the region.
REGION_YMAX=value: defines the north coordinate of the region.
REGION_MIN_LOD_PIXELS=value: Defaults to
256
. minimum size in pixels of the region so that it is displayed.REGION_MAX_LOD_PIXELS=value: Defaults to
-1
. maximum size in pixels of the region so that it is displayed. Defaults to -1 (infinite).REGION_MIN_FADE_EXTENT=value: Defaults to
0
. distance over which the geometry fades, from fully opaque to fully transparent.REGION_MAX_FADE_EXTENT=value: Defaults to
0
. distance over which the geometry fades, from fully transparent to fully opaque.
A <ScreenOverlay> element can be added to display a logo, a legend, etc...
SO_HREF=value: (required) URL of the image to display.
SO_NAME=value:
SO_DESCRIPTION=value:
SO_OVERLAY_X=value:
SO_OVERLAY_Y=value:
SO_OVERLAY_XUNITS=value:
SO_OVERLAY_YUNITS=value:
SO_SCREEN_X=value: Defaults to
0.05
.SO_SCREEN_Y=value: Defaults to
0.05
.SO_SCREEN_XUNITS=value: Defaults to
Fraction
.SO_SCREEN_YUNITS=value: Defaults to
Fraction
.SO_SIZE_X=value:
SO_SIZE_Y=value:
SO_SIZE_XUNITS=value:
SO_SIZE_YUNITS=value:
The following option controls whether layers are written as a Document or a Folder:
FOLDER=[YES/NO]: By default, layers are written as <Document> elements. By setting this option to YES, it is also possible to write them as <Folder> elements (only in .kml files).
The following layer creation options can be used to set container options :
NAME=value: <name> element. Also used to set the name of the NetworkLink pointing to the layer, starting with GDAL 3.10
VISIBILITY=value: <visibility> element
OPEN=value: <open> element
SNIPPET=value: <snippet> element
DESCRIPTION=value: <description> element
Do not confuse them with the same named dataset creation options.
The following layer creation options can be used to control how the folder of a layer appear in the Places panel of the Earth browser, trough a <ListStyle> element:
LISTSTYLE_TYPE=[check/radioFolder/checkOffOnly/checkHideChildren]: Sets the <listItemType> element.
LISTSTYLE_ICON_HREF=value: URL of the icon to display for the layer folder. Sets the href element of the <ItemIcon> element.
Feature
An OGRFeature
generally translates to kml as a
<Placemark>,
and vice-versa.
If the model field is defined, a <Model> object within the Placemark will be generated.
If the networklink field is defined, a <NetworkLink> will be generated. Other networklink fields are optional.
If the photooverlay field is defined, a <PhotoOverlay> will be generated (provided that the camera_longitude, camera_latitude, camera_altitude, camera_altitudemode, head and/or tilt and/or roll, leftfov, rightfov, bottomfov, topfov, near fields are also set. The shape field is optional.
In case the PhotoOverlay is a big image, it is highly recommended to tile it and generate overview levels, as explained in the PhotoOverlay tutorial. In which case, the URL should contain the "$[level]", "$[x]" and "$[y]" sub-strings in the photooverlay field, and the imagepyramid_tilesize, imagepyramid_maxwidth, imagepyramid_maxheight and imagepyramid_gridorigin fields should be set.
Placemark, Model, NetworkLink and PhotoOverlay objects can have an associated camera if the camera_longitude, camera_latitude, camera_altitude, camera_altitudemode, head and/or tilt and/or roll fields are defined.
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.
The following configuration options affect reading of features:
LIBKML_READ_GROUND_OVERLAY=[TRUE/FALSE]: Defaults to
TRUE
. IfFALSE
, skip reading GroundOverlay elements.
Style
Style Strings at the feature level are Mapped to KML as either a <Style> or <StyleUrl> in each <Placemark>.
The following configuration options affect handling of styles:
LIBKML_RESOLVE_STYLE=[YES/NO]: When reading a kml feature and this option 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.
LIBKML_EXTERNAL_STYLE=[YES/NO]: When reading a kml feature and this option 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=NO
then the styleurl is copied to the style string.LIBKML_STYLEMAP_KEY=value: When reading a kml StyleMap the default mapping is set to normal. If you wish to use the highlighted styles set this configuration option to "highlight"
When writing a kml, if there exist 2 styles of the form "astylename_normal" and "astylename_highlight" (where astylename is any string), then a StyleMap object will be creating from both styles and called "astylename".
Fields
OGR fields (feature attributes) are mapped to kml with <Schema>; and <SimpleData>, except for some special fields as noted below.
Note
It is also possible to export fields as <Data> elements using the following configuration option:
LIBKML_USE_SIMPLEFIELD=[YES/NO]: If NO
, export fields as <Data>.
A rich set of configuration options 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 a configuration option. Note these are independent of layer creation and dataset creation options' <name>.
LIBKML_ID_FIELD=value: (GDAL >= 3.10) Defaults to
id
. Name of the string field that maps to the kml attribute <id>.LIBKML_NAME_FIELD=value: Defaults to
name
. Name of the string field that maps to the kml tag <name>.LIBKML_DESCRIPTION_FIELD=value: Defaults to
description
. Name of the string field that maps to the kml tag <description>.LIBKML_TIMESTAMP_FIELD=value: Defaults to
timestamp
. Name of the string/datetime/date/time field that maps to the kml tag <timestamp>.LIBKML_BEGIN_FIELD=value: Defaults to
begin
. Name of the string/datetime/date/time field that maps to the kml tag <begin>.LIBKML_END_FIELD=value: Defaults to
end
. Name of the string/datetime/date/time field that maps to the kml tag <end>.LIBKML_ALTITUDEMODE_FIELD=value: Defaults to
altitudeMode
. Name of the string field that maps to the kml tag <altitudeMode> or <gx:altitudeMode>.LIBKML_TESSELLATE_FIELD=value: Defaults to
tessellate
. Name of the integer field that maps to the kml tag <tessellate>.LIBKML_EXTRUDE_FIELD=value: Defaults to
extrude
. Name of the integer field that maps to the kml tag <extrude>.LIBKML_VISIBILITY_FIELD=value: Defaults to
visibility
. Name of the integer field that maps to the kml tag <visibility>.LIBKML_ICON_FIELD=value: Defaults to
icon
. Name of the string field that maps to the kml tag <icon>.LIBKML_DRAWORDER_FIELD=value: Defaults to
drawOrder
. Name of the integer field that maps to the kml tag <drawOrder>.LIBKML_SNIPPET_FIELD=value: Defaults to
snippet
. Name of the integer field that maps to the kml tag <snippet>.LIBKML_HEADING_FIELD=value: Defaults to
heading
. Name of the real field that maps to the kml tag <heading>. When reading, this field is present only if a Placemark has a Camera with a heading element.LIBKML_TILT_FIELD=value: Defaults to
tilt
. Name of the real field that maps to the kml tag <tilt>. When reading, this field is present only if a Placemark has a Camera with a tilt element.LIBKML_ROLL_FIELD=value: Defaults to
roll
. Name of the real field that maps to the kml tag <roll>. When reading, this field is present only if a Placemark has a Camera with a roll element.LIBKML_MODEL_FIELD=value: Defaults to
model
. Name of the string field that can be used to define the URL of a 3D <model>.LIBKML_SCALE_X_FIELD=value: Defaults to
scale_x
. Name of the real field that maps to the x element of the kml tag <scale> for a 3D model.LIBKML_SCALE_Y_FIELD=value: Defaults to
scale_y
. Name of the real field that maps to the y element of the kml tag <scale>for a 3D model.LIBKML_SCALE_Z_FIELD=value: Defaults to
scale_z
. Name of the real field that maps to the z element of the kml tag <scale>for a 3D model.LIBKML_NETWORKLINK_FIELD=value: Defaults to
networklink
. Name of the string field that maps to the href element of the kml tag <href> of a NetworkLink.LIBKML_NETWORKLINK_REFRESHVISIBILITY_FIELD=value: Defaults to
networklink_refreshvisibility
. Name of the integer field that maps to kml tag <refreshVisibility> of a NetworkLink.LIBKML_NETWORKLINK_FLYTOVIEW_FIELD=value: Defaults to
networklink_flytoview
. Name of the integer field that maps to kml tag <flyToView> of a NetworkLink.LIBKML_NETWORKLINK_REFRESHMODE_FIELD=value: Defaults to
networklink_refreshmode
. Name of the string field that maps to kml tag <refreshMode> of a NetworkLink.LIBKML_NETWORKLINK_REFRESHINTERVAL_FIELD=value: Defaults to
networklink_refreshinterval
. Name of the real field that maps to kml tag <refreshInterval> of a NetworkLink.LIBKML_NETWORKLINK_VIEWREFRESHMODE_FIELD=value: Defaults to
networklink_viewrefreshmode
. Name of the string field that maps to kml tag <viewRefreshMode> of a NetworkLink.LIBKML_NETWORKLINK_VIEWREFRESHTIME_FIELD=value: Defaults to
networklink_viewrefreshtime
. Name of the real field that maps to kml tag <viewRefreshTime> of a NetworkLink.LIBKML_NETWORKLINK_VIEWBOUNDSCALE_FIELD=value: Defaults to
networklink_viewboundscale
. Name of the real field that maps to kml tag <viewBoundScale> of a NetworkLink.LIBKML_NETWORKLINK_HTTPQUERY_FIELD=value: Defaults to
networklink_httpquery
. Name of the string field that maps to kml tag <httpQuery> of a NetworkLink.LIBKML_CAMERA_LONGITUDE_FIELD=value: Defaults to
camera_longitude
. Name of the real field that maps to kml tag <longitude> of a <Camera>.LIBKML_CAMERA_ALTITUDE_FIELD=value: Defaults to
camera_altitude
. Name of the real field that maps to kml tag <altitude> of a <Camera>.LIBKML_CAMERA_ALTITUDEMODE_FIELD=value: Defaults to
camera_altitudemode
. Name of the real field that maps to kml tag <altitudeMode> of a <Camera>.LIBKML_PHOTOOVERLAY_FIELD=value: Defaults to
photooverlay
. Name of the string field that maps to the href element of the kml tag <href> of a <PhotoOverlay>.LIBKML_LEFTFOV_FIELD=value: Defaults to
leftfov
. Name of the real field that maps to to kml tag <LeftFov> of a <PhotoOverlay>.LIBKML_RIGHTFOV_FIELD=value: Defaults to
rightfov
. Name of the real field that maps to to kml tag <RightFov> of a <PhotoOverlay>.LIBKML_BOTTOMFOV_FIELD=value: Defaults to
bottomfov
. Name of the real field that maps to to kml tag <BottomFov> of a <PhotoOverlay>.LIBKML_TOPFOV_FIELD=value: Defaults to
topfov
. Name of the real field that maps to to kml tag <TopFov> of a <PhotoOverlay>.LIBKML_NEARFOV_FIELD=value: Defaults to
near
. Name of the real field that maps to to kml tag <Near> of a <PhotoOverlay>.LIBKML_PHOTOOVERLAY_SHAPE_FIELD=value: Defaults to
shape
. Name of the string field that maps to to kml tag <shape> of a <PhotoOverlay>.LIBKML_IMAGEPYRAMID_TILESIZE=value: Defaults to
imagepyramid_tilesize
. Name of the integer field that maps to to kml tag <tileSize> of a <ImagePyramid>.LIBKML_IMAGEPYRAMID_MAXWIDTH=value: Defaults to
imagepyramid_maxwidth
. Name of the integer field that maps to to kml tag <maxWidth> of a <ImagePyramid>.LIBKML_IMAGEPYRAMID_MAXHEIGHT=value: Defaults to
imagepyramid_maxheight
. Name of the integer field that maps to to kml tag <maxHeight> of a <ImagePyramid>.LIBKML_IMAGEPYRAMID_GRIDORIGIN=value: Defaults to
imagepyramid_gridorigin
. Name of the string field that maps to to kml tag <gridOrigin> of a <ImagePyramid>.OGR_STYLE=value: string field that maps to a features style string, OGR reads this field if there is no style string set on the feature.
Geometry
Translation of OGRGeometry
to
KML Geometry is pretty straightforward with only a couple of exceptions.
Point to
<Point>
(unless heading and/or tilt and/or roll field names are found, in which
case a
Camera
object will be generated), 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.
The following configuration options control geometry translation:
LIBKML_WRAPDATELINE=[YES/NO]: 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 this to "yes" will cause the libkml driver to split the geometry at the dateline when read.
VSI Virtual File System API support
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.
Examples
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
The following example shows how the three levels of <name> in LIBKML relate to their controlling options:
ogr2ogr -f LIBKML /dev/stdout 0.contours.csv \
-dsco NAME=DSCO -lco NAME=LCO \
-sql 'SELECT NAME FROM "0.contours"'
<Document id="root_doc">
<name>DSCO</name>
<Document id="_0.contours">
<name>LCO</name>
<Placemark id="_0.contours.1">
<name>-1500</name>
<LineString>