Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@tmcw/togeojson

placemark265.4kBSD-2-Clause7.1.1TypeScript support: included

convert KML and GPX to GeoJSON

kml, geojson, gpx, tcx, geo, parser, formatter, input, leaflet, maps

readme

Convert KML, GPX, and TCX to GeoJSON.

NPM Version

togeojson development is supported by 🌎 placemark.io

This converts KML, TCX, & GPX to GeoJSON, in a browser or with Node.js.

  • <input checked="" disabled="" type="checkbox"> Dependency-free
  • <input checked="" disabled="" type="checkbox"> Tiny
  • <input checked="" disabled="" type="checkbox"> Tested
  • <input checked="" disabled="" type="checkbox"> Node.js + Browsers

📕 API Documentation

This is a JavaScript library that lets projects convert KML and GPX to GeoJSON. If you're looking for a command line too, use @tmcw/togeojson-cli. If you want to convert one KML or GPX file, use my online tool. If you want to convert another format, consider GDAL.

Property conversions

In addition to converting KML’s <ExtendedData> verbatim, @tmcw/togeojson also encodes parts of KML, GPX, and TCX files that otherwise would be lost.

KML

  • Style properties: fill-color, fill-opacity, stroke, stroke-opacity, icon-color, icon-opacity, label-color, label-opacity, icon-scale, icon-heading, icon-offset, icon-offset-units

GPX

  • Style properties: stroke, stroke-opacity, stroke-width

TCX

  • Line properties: totalTimeSeconds, distanceMeters, maxSpeed, avgHeartRate, maxHeartRate, avgSpeed, avgWatts, maxWatts

This also emits the geojson-coordinate-properties format to include time and other attributes that apply to each coordinate of a LineString.

Ground overlays

Example of working with Ground Overlays in Mapbox GL JS

KML GroundOverlays are now supported, and transformed into Features with Polygon geometries. They have two defined properties:

{
  "@geometry-type": "groundoverlay",
  "icon": "https://url.to.image…"
}

Both gx:LatLonQuad and LatLonBox-based ground overlays are supported.

TypeScript

If you're using this with TypeScript, you'll want to also install:

  • @types/geojson
  • @xmldom/xmldom

These will give you accurate types for both input and output types. Due to TypeScript limitations, it's currently necessary to install @xmldom/xmldom for accurate input types even if you aren't using that module for parsing XML. If you have ideas for how to improve this, please comment on this PR!.

CLI

Use @tmcw/togeojson-cli to use this software as a command-line tool.

Node.js

Install it into your project with npm install --save @tmcw/togeojson.

// using togeojson in nodejs

const tj = require("@tmcw/togeojson");
const fs = require("fs");
// node doesn't have xml parsing or a dom. use xmldom
const DOMParser = require("xmldom").DOMParser;

const kml = new DOMParser().parseFromString(fs.readFileSync("foo.kml", "utf8"));

const converted = tj.kml(kml);

ES Modules

// The ES Module provides named exports, to import kml, gpx,
// and other parts of the module by name.
import { kml } from "@tmcw/togeojson";

Browser

<script type="module">
  import { kml } from "https://unpkg.com/@tmcw/togeojson?module";

  fetch("test/data/linestring.kml")
    .then(function (response) {
      return response.text();
    })
    .then(function (xml) {
      console.log(kml(new DOMParser().parseFromString(xml, "text/xml")));
    });
</script>

KML Feature Support

  • <input checked="" disabled="" type="checkbox"> Point
  • <input checked="" disabled="" type="checkbox"> Polygon
  • <input checked="" disabled="" type="checkbox"> LineString
  • <input checked="" disabled="" type="checkbox"> name & description
  • <input checked="" disabled="" type="checkbox"> ExtendedData
  • <input checked="" disabled="" type="checkbox"> SimpleData
  • <input checked="" disabled="" type="checkbox"> MultiGeometry -> GeometryCollection
  • <input checked="" disabled="" type="checkbox"> Styles
  • <input checked="" disabled="" type="checkbox"> Tracks & MultiTracks with gx:coords, including altitude
  • <input checked="" disabled="" type="checkbox"> TimeSpan
  • <input checked="" disabled="" type="checkbox"> TimeStamp
  • <input checked="" disabled="" type="checkbox"> Folders (with kmlWithFolders)
  • <input checked="" disabled="" type="checkbox"> GroundOverlays
  • <input disabled="" type="checkbox"> NetworkLinks

GPX Feature Support

  • <input checked="" disabled="" type="checkbox"> Line Paths
  • <input checked="" disabled="" type="checkbox"> Line styles
  • <input disabled="" type="checkbox"> Properties
    • <input checked="" disabled="" type="checkbox"> 'name', 'cmt', 'desc', 'link', 'time', 'keywords', 'sym', 'type' tags
    • <input checked="" disabled="" type="checkbox"> gpxx Garmin extensions on tracks and routes
    • <input disabled="" type="checkbox"> 'author', 'copyright' tags

FAQ

How does this differ from mapbox/togeojson?

  • This repository is maintained.
  • It’s available as an ES Module. If you're using a modern JavaScript bundler or using ES Modules in the browser, this makes it a bit more efficient and sometimes easier to use.
  • Conversion methods are available as generators, which makes the conversion of big files more efficient.
  • The command line utility was moved to tmcw/togeojson-cli, which lets this module enjoy reduced dependencies: installing @tmcw/togeojson doesn’t require any other dependencies.

The NetworkLink KML construct allows KML files to refer to other online or local KML files for their content. It's often used to let people pass around files but keep the actual content on servers.

In order to support NetworkLinks, toGeoJSON would need to be asynchronous and perform network requests. These changes would make it more complex and less reliable in order to hit a limited usecase - we'd rather keep it simple and not require users to think about network connectivity and bandwith in order to convert files.

NetworkLink support could be implemented in a separate library as a pre-processing step if desired.

Should toGeoJSON support feature X from KML?

This module should support converting all KML and GPX features that have commonplace equivalents in GeoJSON.

Protips:

Have a string of XML and need an XML DOM? There are two main options:

  • Use xmldom, a JavaScript module that contains its own XML parser
  • Use DOMParser, the native platform XML parser

We recommend that you use xmldom, not the platform. DOMParser requires XML to be valid, which means that any XML namespaces that a KML, GPX, or TCX file contains are valid. A lot of existing data is invalid XML, and will be parsed only in part by DOMParser, but can be fully parsed by xmldom.

Using xmldom (recommended):

const xmldom = require("@xmldom/xmldom");
const dom = new xmldom.DOMParser().parseFromString(xmlStr, "text/xml");

Using DOMParser:

var dom = new DOMParser().parseFromString(xmlStr, "text/xml");

Maintainability Test Coverage

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

5.6.2 (2023-05-30)

Bug Fixes

  • Zero elevation data in GPX should still be included (6457106)

5.6.1 (2023-05-05)

Bug Fixes

  • adds types definitions to exports in package.json (#109) (f382d30)

5.6.0 (2022-12-30)

Features

  • Support LinearRing as direct descendent of a Placemark element (#105) (3673a7f)

Bug Fixes

5.5.0 (2022-11-12)

Features

  • Add support for Schema tag and convert properties to correct datatype (#100) (22479aa), closes #69

5.4.0 (2022-10-31)

Features

5.3.0 (2022-10-23)

Features

Bug Fixes

  • properly support KMLs with sibling MultiGeometries (#96) (f0e978a)

5.2.2 (2022-08-09)

5.2.1 (2022-06-15)

Bug Fixes

  • Limit extracted coordinates to 3 (#91) (b35d5a2)

5.2.0 (2022-06-12)

Features

5.2.0-1 (2022-06-12)

Bug Fixes

5.2.0-0 (2022-06-12)

Features

  • Handle HTML in description tags (e156191)

5.1.3 (2022-05-22)

Bug Fixes

  • Switch ESM entry point to use .mjs ending to fix Node.js native ESM support (cd366b8)

5.1.3-0 (2022-05-22)

5.1.2 (2022-04-24)

Bug Fixes

  • Add fixtures, block invalid GPX inputs (#80) (d57cd80)

5.1.1 (2022-04-24)

Bug Fixes

  • Add fixtures, block invalid GPX inputs (#80) (d57cd80)

5.1.0 (2022-04-23)

Features

5.0.0 (2022-04-22)

Bug Fixes

5.0.0-5 (2022-03-19)

Bug Fixes

5.0.0-4 (2022-03-15)

Bug Fixes

  • Allow meta object to contain new values (6dd282e)

5.0.0-3 (2022-03-15)

Bug Fixes

  • Export Folder and Root types (b9fa7f0)

5.0.0-2 (2022-03-14)

5.0.0-1 (2022-03-14)

5.0.0-0 (2022-03-14)

4.8.0-0 (2022-03-14)

Features

4.7.1-0 (2022-03-09)

4.7.0 (2022-03-08)

Features

  • Support gx:CascadingStyle (600c542)

4.6.1 (2022-03-07)

4.6.1-1 (2022-03-07)

Bug Fixes

4.6.1-0 (2022-03-07)

Bug Fixes

  • Make module system more convoluted (845ff7a)

4.6.0 (2022-03-07)

Features

  • Support additional GPX extensions (ae2f00f)

4.5.0 (2021-08-03)

Features

4.4.1 (2021-04-27)

Bug Fixes

  • Rename heartRates coordinate property to heart (#48) (8fc03f2)

4.4.0 (2021-03-31)

Features

  • Add coordinate properties for times and heartRates (#47) (5e3958b)

4.3.0 (2020-12-28)

Features

  • Add heartRates to geojson properties for tcx files (#42) (ecde092)

4.2.0 (2020-09-05)

Features

  • Preserve GPX linestring type in a _gpxType property that is either rte or trk (54fa558)
  • TCX Support (6df0878)

4.1.0 (2020-06-13)

Features

  • Add LabelStyle support and complete IconStyle support for KML (f920b16)

4.0.0 (2020-04-05)

⚠ BREAKING CHANGES

  • Previously, togeojson would ignore Placemarks that did not have associated geometry. Per the GeoJSON specification, Feature objects can have null geometries. After this change, togeojson will output features with null geometries as the translation of KML Placemarks with no geometry, instead of ommitting those items entirely.

3.2.0 (2019-12-29)

Features

  • add garmin extension handling (2e95798)

3.1.0 (2019-12-25)

Features

  • Add parsing of GPX extensions speed, course, hAcc, vAcc (#18) (99301bd)

3.0.1 (2019-06-17)

Bug Fixes

  • Typo in rollup configuration (1af08f6)

3.0.0 (2019-03-28)

Code Refactoring

  • switch from initializeArray to Array.fill (#11) (dac617a), closes #10

BREAKING CHANGES

  • this may modify browser support if you’re using an old browser. See the MDN page for full details:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

2.0.0 (2019-03-08)

Features

  • Generator methods, removed CLI (f37a30b)

BREAKING CHANGES

  • the cli that was previously installed along with togeojson has been removed, and will be installable as @tmcw/togeojson-cli

Other changes in this pass:

  • Switch from microbundle to rollup to build
  • Remove dependencies
  • Remove reliance on XMLSerializer. This will make togeojson work in worker contexts.

1.0.0 (2019-01-18)

1.0.0-alpha.1 (2019-01-18)

1.0.0-alpha.0 (2019-01-18)

0.16.0

  • Supports the link tag in GPX data.
  • Supports the type tag for waypoints in GPX data.

0.15.0

  • Supports the cmt (comment) tag in GPX data.

0.14.2

  • Fixes a potential crash with QGIS-generated GPX files.

0.14.0

  • Now includes TimeStamp property from Placemarks, if it exists.

0.13.0

  • Added support for StyleMap elements in Google-flavored KML
  • Improved test coverage
  • Made # prefix for internal style references optional
  • Uses eslint for code style uniformity

0.12.2

  • Fix # prefix on exported hex colors

0.12.1

  • Fix trackpoints with elevation=0 having their elevation skipped

0.12.0

  • Fix rte based GPX based tracks
  • Add CDATA support to KML

0.11.0

  • Add heartrate support for GPX tracks
  • Fix elevation support
  • Fix test runner

0.10.1

  • Fix an IE9 error: IE9 'supports' XMLSerializer inasmuch as it will create an instance that fails always and hard.

0.10.0

  • Encode timestamps along lines in GPX and KML as a coordTimes property.

0.9.0

  • Encode KML id attributes on Placemarks as GeoJSON Feature id properties.

0.8.0

  • Support for the gx:Track and gx:MultiTrack extensions to GPX

0.7.0

  • GPX conversion creates MultiLineString geometries when given multiple track segments.

0.6.0

0.5.0

  • Elevation values along linestrings and in points for GPX are now parsed correctly into Z coordinate values in GeoJSON.

0.4.2

  • No longer bundles xmldom for browsers

0.3.1

  • Stricter check for browser versus browserify when requiring xmldom

0.3.0

  • Support for pipes and streams
echo "LineString(0 0, 10 10)" | wellknown | tokml | togeojson > map.geojson

0.2.0

  • Improve documentation
  • Make style hashing on by default, remove options object

0.1.1

  • Fix global leak.

0.1.0

  • Comments
  • GPX Support

0.0.1

  • Support GeometryCollections as themselves.