@tmcw/togeojson

repository·main·Indexed 19 days ago

https://github.com/placemark/togeojson

A lightweight, dependency-free library for converting KML, GPX, and TCX files into GeoJSON format, and vice versa. It works in Node.js and browser environments, providing functions like kml(), gpx(), and tcx() for conversion, as well as generator functions (kmlGen, gpxGen, tcxGen) to create KML, GPX, or TCX from GeoJSON. The library supports KML Ground Overlays, hierarchical folder extraction via kmlWithFolders(), and preserves specific style and metadata properties.

Tokens
2K
Snippets
12
Records
16
Agent score
65%

What's inside @tmcw/togeojson

  1. How KML, GPX, and TCX properties are converted

    main

    The library encodes specific metadata that would otherwise be lost during conversion:

    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

    Additionally, the library emits the geojson-coordinate-properties format to include time and other attributes for each coordinate in a LineString.

  2. How KML Ground Overlays are handled

    main

    KML GroundOverlays are supported and transformed into GeoJSON Features with Polygon geometries. These features include two specific properties:

    • @geometry-type: set to "groundoverlay"
    • icon: the URL to the image

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

  3. Install @tmcw/togeojson

    main

    To use this library in your project, install it via npm:

    npm install --save @tmcw/togeojson

    If you are using TypeScript, it is recommended to also install @types/geojson and @xmldom/xmldom to ensure accurate typing for both input and output data structures.

  4. How GroundOverlays are handled in KML conversion

    main

    In KML, GroundOverlay elements are used to overlay images on a map. When converted to GeoJSON via kml() or kmlGen(), they are transformed into Feature objects with Polygon geometries.

    To identify a feature as a ground overlay, look for the following property in its metadata:

    {
      "@geometry-type": "groundoverlay"
    }

    The image URL from the KML href attribute is preserved in the href property of the feature.

  5. Convert KML to GeoJSON in Node.js

    main

    In a Node.js environment, you must provide a DOM object to the conversion functions. Since Node.js does not have a native DOM, it is highly recommended to use @xmldom/xmldom to parse your XML strings into a DOM. Using xmldom is preferred over native platform parsers because it is more resilient to XML namespaces and invalid XML often found in KML/GPX files.

    To convert KML, use the kml() function.

    const tj = require("@tmcw/togeojson");
    const fs = require("fs");
    const DOMParser = require("xmldom").DOMParser;
    
    const kml = new DOMParser().parseFromString(fs.readFileSync("foo.kml", "utf8"));
    const converted = tj.kml(kml);
  6. Convert KML to GeoJSON in the Browser

    main

    You can use the library directly in a browser by importing it as an ES Module from a CDN like unpkg. You will need to use the browser's native DOMParser to convert your XML text into a DOM object before passing it to the converter.

    <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>
  7. Configure KML conversion options

    main

    When converting KML to GeoJSON, you can provide a KMLOptions object to customize the output.

    Currently, the only available option is skipNullGeometry. By default, togeojson translates KML features without geometries (e.g., a Placemark without a Point element) into GeoJSON features with a null geometry. If your target system does not support null geometries, set skipNullGeometry: true to omit these features entirely.

    const options: KMLOptions = {
      skipNullGeometry: true
    };
  8. Convert KML to GeoJSON using kml()

    main

    Use the kml function to convert KML data into GeoJSON. For KML structures that include folders, you can also use kmlWithFolders to ensure the hierarchy is preserved in the resulting GeoJSON.

    import { kml, kmlWithFolders } from '@tmcw/togeojson';
    
    // Standard KML conversion
    const geojson = kml(kmlDocument);
    
    // KML conversion preserving folder hierarchy
    const geojsonWithFolders = kmlWithFolders(kmlDocument);
  9. Convert KML to GeoJSON with kml()

    main

    The kml() function converts a KML document into a complete GeoJSON FeatureCollection.

    Important: The first argument must be an XML DOM Document (or XDocument), not a raw string. You can obtain a DOM using standard browser APIs like XMLHttpRequest or libraries like xmldom.

    import { kml } from '@tmcw/togeojson';
    
    // 'node' must be an XML DOM Document
    const geojson = kml(node, { skipNullGeometry: true });