kml2geojson 5.1.0 Documentation

Introduction

kml2geojson is a Python 3.8+ package to convert KML files to GeoJSON files. Most of its code is a translation into Python of the Node.js package togeojson, but kml2geojson also adds the following features.

  • Preserve KML object styling, such as color and opacity

  • Optionally create a style dictionary cataloging all the KML styles used

  • Optionally create several GeoJSON FeatureCollections, one for each KML folder present

Installation

Create a Python 3.8+ virtual environment and run poetry add kml2geojson.

Usage

Use as a library or from the command line. For instructions on the latter, type k2g --help.

Documentation

In the docs directory and published at mrcagney.github.io/kml2geojson_docs.

Notes

  • Development status is Alpha.

  • This project uses semantic versioning.

Authors

  • Alex Raichev (2015-10-03), maintainer

API

The kml2geojson package contains two independent modules, main and cli, the latter of which is a command line interface for the package.

kml2geojson.main module

kml2geojson.main.GEOTYPES = ['Polygon', 'LineString', 'Point', 'Track', 'gx:Track']

Atomic KML geometry types supported. MultiGeometry is handled separately.

kml2geojson.main.STYLE_TYPES = ['svg', 'leaflet']

Supported style types

kml2geojson.main.attr(node: xml.dom.minidom.Document, name: str) str

Return as a string the value of the given DOM node’s attribute named by name, if it exists. Otherwise, return an empty string.

kml2geojson.main.build_feature(node: xml.dom.minidom.Document) dict | None

Build and return a (decoded) GeoJSON Feature corresponding to this KML node (typically a KML Placemark). Return None if no Feature can be built.

kml2geojson.main.build_feature_collection(node: xml.dom.minidom.Document, name: Optional[str] = None) dict

Build and return a (decoded) GeoJSON FeatureCollection corresponding to this KML DOM node (typically a KML Folder). If a name is given, store it in the FeatureCollection’s 'name' attribute.

kml2geojson.main.build_geometry(node: xml.dom.minidom.Document) dict

Return a (decoded) GeoJSON geometry dictionary corresponding to the given KML node.

kml2geojson.main.build_layers(node: xml.dom.minidom.Document, *, disambiguate_names: bool = True) list[dict]

Return a list of GeoJSON FeatureCollections, one for each folder in the given KML DOM node that contains geodata. Name each FeatureCollection (via a 'name' attribute) according to its corresponding KML folder name.

If disambiguate_names == True, then disambiguate repeated layer names via disambiguate().

Warning: this can produce layers with the same geodata in case the KML node has nested folders with geodata.

kml2geojson.main.build_leaflet_style(node: xml.dom.minidom.Document) dict

Given a DOM node, grab its top-level Style nodes, convert every one into a Leaflet style dictionary, put them in a master dictionary of the form

#style ID -> Leaflet style dictionary,

and return the result.

The the possible keys and values of each Leaflet style dictionary, the style options, are

  • iconUrl: URL of icon

  • color: stroke color; RGB hex string

  • opacity: stroke opacity

  • weight: stroke width in pixels

  • fillColor: fill color; RGB hex string

  • fillOpacity: fill opacity

kml2geojson.main.build_rgb_and_opacity(s: str) tuple

Given a KML color string, return an equivalent RGB hex color string and an opacity float rounded to 2 decimal places.

EXAMPLE:

>>> build_rgb_and_opacity('ee001122')
('#221100', 0.93)
kml2geojson.main.build_svg_style(node: xml.dom.minidom.Document) dict

Given a DOM node, grab its top-level Style nodes, convert every one into a SVG style dictionary, put them in a master dictionary of the form

#style ID -> SVG style dictionary,

and return the result.

The possible keys and values of each SVG style dictionary, the style options, are

  • iconUrl: URL of icon

  • stroke: stroke color; RGB hex string

  • stroke-opacity: stroke opacity

  • stroke-width: stroke width in pixels

  • fill: fill color; RGB hex string

  • fill-opacity: fill opacity

kml2geojson.main.convert(kml_path_or_buffer: str | pathlib.Path | TextIO | BinaryIO, feature_collection_name: Optional[str] = None, style_type: Optional[str] = None, *, separate_folders: bool = False)

Given a path to a KML file or given a KML file object, convert it to a single GeoJSON FeatureCollection dictionary named feature_collection_name. Close the KML file afterwards.

If separate_folders, then return several FeatureCollections, one for each folder in the KML file that contains geodata or that has a descendant node that contains geodata. Warning: this can produce FeatureCollections with the same geodata in case the KML file has nested folders with geodata.

If a style type from STYLE_TYPES is given, then also create a JSON dictionary that encodes into the style type the style information contained in the KML file.

Return a tuple (style dict, FeatureCollection 1, …, FeatureCollection n), where the style dict is present if and only if style_type is given and where n > 1 if and only if separate_folders and the KML file contains more than one folder of geodata.

kml2geojson.main.coords(s: str) list[list[float]]

Convert the given KML string containing multiple coordinate tuples into a list of lists of floats.

EXAMPLE:

>>> coords('''
... -112.0,36.1,0
... -113.0,36.0,0
... ''')
[[-112.0, 36.1, 0.0], [-113.0, 36.0, 0.0]]
kml2geojson.main.coords1(s: str) list[float]

Convert the given KML string containing one coordinate tuple into a list of floats.

EXAMPLE:

>>> coords1(' -112.2,36.0,2357 ')
[-112.2, 36.0, 2357.0]
kml2geojson.main.disambiguate(names: list[str], mark: str = '1') list[str]

Given a list of strings names, return a new list of names where repeated names have been disambiguated by repeatedly appending the given mark.

EXAMPLE:

>>> disambiguate(['sing', 'song', 'sing', 'sing'])
['sing', 'song', 'sing1', 'sing11']
kml2geojson.main.get(node: md.Document, name: str) mc.Nodelist

Given a KML Document Object Model (DOM) node, return a list of its sub-nodes that have the given tag name.

kml2geojson.main.get1(node: xml.dom.minidom.Document, name: str) xml.dom.minidom.Element | None

Return the first element of get(node, name), if it exists. Otherwise return None.

kml2geojson.main.gx_coords(node: xml.dom.minidom.Document) dict

Given a KML DOM node, grab its <gx:coord> and <gx:timestamp><when>subnodes, and convert them into a dictionary with the keys and values

  • 'coordinates': list of lists of float coordinates

  • 'times': list of timestamps corresponding to the coordinates

kml2geojson.main.gx_coords1(s: str) list[float]

Convert the given KML string containing one gx coordinate tuple into a list of floats.

EXAMPLE:

>>> gx_coords1('-113.0 36.0 0')
[-113.0, 36.0, 0.0]
kml2geojson.main.numarray(a: list) list[float]

Cast the given list into a list of floats.

kml2geojson.main.to_filename(s: str) str

Based on django/utils/text.py. Return the given string converted to a string that can be used for a clean filename. Specifically, leading and trailing spaces are removed; other spaces are converted to underscores, and anything that is not a unicode alphanumeric, dash, underscore, or dot, is removed.

EXAMPLE:

>>> to_filename("%  A dbla'{-+)(ç? ")
'A_dsbla-ç'
kml2geojson.main.val(node: xml.dom.minidom.Document) str

Normalize the given DOM node and return the value of its first child (the string content of the node) stripped of leading and trailing whitespace.

kml2geojson.main.valf(node: xml.dom.minidom.Document) float

Cast val(node) as a float. Return None if that does not work.

kml2geojson.cli module

Sphinx auto-documentation does not work on this module, because all the functions inside are decorated by Click decorators, which don’t play nicely with Sphinx. So use the command line to access the documentation for k2g, the command line interface for kml2geojson:

~> k2g --help
Usage: k2g [OPTIONS] KML_PATH OUTPUT_DIR

Given a path to a KML file, convert it to a a GeoJSON FeatureCollection
file and save it to the given output directory.

If ``--separate_folders``, then create several GeoJSON files, one for each
folder in the KML file that contains geodata or that has a descendant node
that contains geodata. Warning: this can produce GeoJSON files with the
same geodata in case the KML file has nested folders with geodata.

If ``--style_type`` is specified, then also build a JSON style file of the
given style type and save it to the output directory under the file name
given by ``--style_filename``.

Options:
  -f, --separate-folders
  -st, --style-type [svg|leaflet]
  -sf, --style-filename TEXT
  --help                          Show this message and exit.

Indices and tables