### Convert KML to GeoJSON in Browser (ES Modules)
Source: https://github.com/tmcw/togeojson/blob/main/docs/index.html
This example shows how to import and use the kml conversion function from @tmcw/togeojson in a browser environment using ES Modules. It fetches a KML file, parses its XML content, and then converts it to GeoJSON, logging the result to the console. This approach leverages modern browser JavaScript features.
```javascript
```
--------------------------------
### Implement File Conversion in the Browser
Source: https://context7.com/tmcw/togeojson/llms.txt
Shows how to use @tmcw/togeojson in a browser environment via ES modules. It includes a file input handler that detects file extensions and converts KML, GPX, or TCX files to GeoJSON.
```html
```
--------------------------------
### Browser KML Conversion with ES Modules
Source: https://github.com/tmcw/togeojson/blob/main/README.md
Illustrates how to use the togeojson library in a web browser by importing it as an ES Module via a CDN. It fetches a KML file, parses it using DOMParser, and logs the resulting GeoJSON to the console.
```html
```
--------------------------------
### Convert GPX to GeoJSON
Source: https://context7.com/tmcw/togeojson/llms.txt
Demonstrates how to parse a GPX file into a DOM object and convert it into a GeoJSON FeatureCollection. It also shows how to access track metadata, timestamps, and extension data like heart rate.
```javascript
const tj = require("@tmcw/togeojson");
const { DOMParser } = require("@xmldom/xmldom");
const fs = require("fs");
const gpxString = fs.readFileSync("running_track.gpx", "utf8");
const gpxDom = new DOMParser().parseFromString(gpxString, "text/xml");
const geojson = tj.gpx(gpxDom);
geojson.features.forEach(feature => {
const props = feature.properties;
console.log(`Track: ${props.name}`);
console.log(`Type: ${props._gpxType}`);
if (props.coordinateProperties?.times) {
console.log(`Start: ${props.coordinateProperties.times[0]}`);
}
});
```
--------------------------------
### ES Module Import for KML Conversion
Source: https://github.com/tmcw/togeojson/blob/main/README.md
Shows how to import the 'kml' conversion function using ES Module syntax, allowing for named imports of specific functionalities from the @tmcw/togeojson library.
```javascript
// The ES Module provides named exports, to import kml, gpx,
// and other parts of the module by name.
import { kml } from "@tmcw/togeojson";
```
--------------------------------
### Import KML conversion function as ES Module
Source: https://github.com/tmcw/togeojson/blob/main/docs/index.html
This snippet illustrates how to import specific functions, like 'kml', from the @tmcw/togeojson library when using ES Modules. This allows for targeted imports, making the code cleaner and more efficient by only bringing in the necessary components.
```javascript
import { kml } from "@tmcw/togeojson";
```
--------------------------------
### Convert KML Styles to GeoJSON Properties
Source: https://context7.com/tmcw/togeojson/llms.txt
Demonstrates how to parse a KML file containing style definitions and convert them into GeoJSON properties following the simplestyle-spec. This includes mapping stroke, fill, and opacity values.
```javascript
const tj = require("@tmcw/togeojson");
const { DOMParser } = require("@xmldom/xmldom");
const styledKml = `
#redLineStyled Path-122.36,37.82,0 -122.36,37.82,0`;
const dom = new DOMParser().parseFromString(styledKml, "text/xml");
const geojson = tj.kml(dom);
console.log(geojson.features[0].properties);
```
--------------------------------
### Node.js KML Conversion
Source: https://github.com/tmcw/togeojson/blob/main/README.md
Demonstrates how to use the togeojson library in a Node.js environment to parse a KML file and convert it to GeoJSON. It requires the 'xmldom' package for XML parsing.
```javascript
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);
```
--------------------------------
### Convert TCX to GeoJSON in Node.js
Source: https://context7.com/tmcw/togeojson/llms.txt
Demonstrates how to parse a TCX file using @xmldom/xmldom and convert it into a GeoJSON FeatureCollection. It also shows how to extract and analyze fitness metrics like duration, distance, and heart rate from the resulting object.
```javascript
const tj = require("@tmcw/togeojson");
const { DOMParser } = require("@xmldom/xmldom");
const fs = require("fs");
const tcxString = fs.readFileSync("workout.tcx", "utf8");
const tcxDom = new DOMParser().parseFromString(tcxString, "text/xml");
const geojson = tj.tcx(tcxDom);
console.log(JSON.stringify(geojson, null, 2));
geojson.features.forEach((lap, index) => {
const p = lap.properties;
console.log(`Lap ${index + 1}:`);
console.log(` Duration: ${(p.totalTimeSeconds / 60).toFixed(1)} minutes`);
console.log(` Distance: ${(p.distanceMeters / 1000).toFixed(2)} km`);
});
```
--------------------------------
### kmlWithFolders
Source: https://github.com/tmcw/togeojson/blob/main/docs/modules.html
Yields a nested tree with KML folder structure. GroundOverlay elements are converted into Feature objects with Polygon geometries.
```APIDOC
## kmlWithFolders
### Description
Yield a nested tree with KML folder structure. This generates a tree with the given structure:
{
"type": "root",
"children": [
{
"type": "folder",
"meta": {
"name": "Test"
},
"children": [
// ...features and folders
]
}
// ...features
]
}
GroundOverlay elements are converted into `Feature` objects with `Polygon` geometries, a property like:
{
"@geometry-type": "groundoverlay"
}
And the ground overlay's image URL in the `href` property. Ground overlays will need to be displayed with a separate method to other features, depending on which map framework you're using.
### Method
Not specified (likely a function call)
### Endpoint
Not applicable (this is a library function)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **Root** (object) - The root of the nested tree structure.
#### Response Example
```json
{
"type": "root",
"children": [
{
"type": "folder",
"meta": {
"name": "Example Folder"
},
"children": [
// ... features and sub-folders
]
}
]
}
```
```
--------------------------------
### KMLOptions Interface
Source: https://github.com/tmcw/togeojson/blob/main/docs/interfaces/KMLOptions.html
Options to customize KML output. This interface allows for controlling how null geometries are handled during the conversion process.
```APIDOC
## Interface KMLOptions
### Description
Options to customize KML output. The only option currently is `skipNullGeometry`. Both KML and GeoJSON formats support features without geometries. In KML, this is a Placemark without a Point, etc element, and in GeoJSON, it's a geometry member with a value of `null`.
toGeoJSON, by default, translates null geometries in KML to null geometries in GeoJSON. For systems that use GeoJSON but don't support null geometries, you can specify `skipNullGeometry` to omit these features entirely and only include features that have a geometry defined.
### Properties
#### Optional skipNullGeometry
- **skipNullGeometry** (boolean) - Optional - If true, features with null geometries will be omitted from the output.
```
--------------------------------
### Parse XML String to DOM using xmldom
Source: https://github.com/tmcw/togeojson/blob/main/README.md
This snippet demonstrates how to parse an XML string into a DOM object using the recommended xmldom library. It handles potentially invalid XML more robustly than the native DOMParser.
```javascript
const xmldom = require("@xmldom/xmldom");
const dom = new xmldom.DOMParser().parseFromString(xmlStr, "text/xml");
```
--------------------------------
### Convert KML GroundOverlays to GeoJSON
Source: https://context7.com/tmcw/togeojson/llms.txt
Shows the conversion of KML GroundOverlay elements into GeoJSON features. The resulting feature includes the image URL in the icon property and a Polygon geometry representing the LatLonBox bounds.
```javascript
const tj = require("@tmcw/togeojson");
const { DOMParser } = require("@xmldom/xmldom");
const overlayKml = `
Historic Maphttps://example.com/historic-map.png37.8337.82-122.36-122.37`;
const dom = new DOMParser().parseFromString(overlayKml, "text/xml");
const geojson = tj.kml(dom);
const overlay = geojson.features[0];
console.log(overlay.properties);
console.log(overlay.geometry.type);
```
--------------------------------
### Generate GPX to GeoJSON Incrementally - JavaScript
Source: https://github.com/tmcw/togeojson/blob/main/docs/modules.html
Provides a generator function to convert GPX to GeoJSON incrementally, yielding features one by one. This approach is memory-efficient for handling large GPX files.
```javascript
import { gpxGen } from "@tmcw/togeojson";
// Assuming 'gpxDom' is an XML Document object representing GPX data
const featureGenerator = gpxGen(gpxDom);
for (const feature of featureGenerator) {
console.log(feature);
}
```
--------------------------------
### Parse XML String to DOM using DOMParser
Source: https://github.com/tmcw/togeojson/blob/main/README.md
This snippet shows how to parse an XML string into a DOM object using the native DOMParser. Note that this method requires the XML to be strictly valid and may fail on malformed XML.
```javascript
var dom = new DOMParser().parseFromString(xmlStr, "text/xml");
```
--------------------------------
### Generate KML to GeoJSON Incrementally - JavaScript
Source: https://github.com/tmcw/togeojson/blob/main/docs/modules.html
Provides a generator function to convert KML to GeoJSON incrementally, yielding features one by one. This is useful for processing large KML files efficiently without loading the entire document into memory at once.
```javascript
import { kmlGen } from "@tmcw/togeojson";
// Assuming 'kmlDom' is an XML Document object representing KML data
const featureGenerator = kmlGen(kmlDom, options);
for (const feature of featureGenerator) {
console.log(feature);
}
```
--------------------------------
### Convert KML to GeoJSON in Node.js
Source: https://github.com/tmcw/togeojson/blob/main/docs/index.html
This snippet demonstrates how to use the @tmcw/togeojson library in a Node.js environment to convert a KML file to GeoJSON. It requires the 'xmldom' package for XML parsing as Node.js does not have a built-in DOM parser. The code reads a KML file, parses it into an XML document, and then uses the kml function to convert it.
```javascript
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);
```
--------------------------------
### Convert GPX Document to GeoJSON - JavaScript
Source: https://github.com/tmcw/togeojson/blob/main/docs/modules.html
Converts a GPX document (provided as an XML DOM) into a GeoJSON FeatureCollection. The output includes a '_gpxType' property on LineString features indicating if they were routes ('rte') or tracks ('trk') in the GPX data.
```javascript
import { gpx } from "@tmcw/togeojson";
// Assuming 'gpxDom' is an XML Document object representing GPX data
const geojsonData = gpx(gpxDom);
console.log(JSON.stringify(geojsonData));
```
--------------------------------
### GPX Conversion API
Source: https://github.com/tmcw/togeojson/blob/main/docs/index.html
Methods for converting GPX data into GeoJSON format.
```APIDOC
## gpx(doc)
### Description
Converts a GPX document into GeoJSON.
### Method
Function Call
### Parameters
#### Path Parameters
- **doc** (Document) - Required - The XML DOM object representing the GPX file.
### Response
#### Success Response (Object)
- **type** (string) - The GeoJSON feature collection.
```
--------------------------------
### Process TCX Incrementally with Generators
Source: https://context7.com/tmcw/togeojson/llms.txt
Uses the tcxGen generator to process TCX files lap-by-lap. This approach is memory-efficient for large workout files as it yields features one at a time.
```javascript
const tj = require("@tmcw/togeojson");
const { DOMParser } = require("@xmldom/xmldom");
const fs = require("fs");
const tcxString = fs.readFileSync("marathon.tcx", "utf8");
const tcxDom = new DOMParser().parseFromString(tcxString, "text/xml");
let lapNumber = 0;
for (const lap of tj.tcxGen(tcxDom)) {
lapNumber++;
console.log(`Lap ${lapNumber}: ${(lap.properties.distanceMeters / 1000).toFixed(2)} km`);
}
```
--------------------------------
### tcxGen
Source: https://github.com/tmcw/togeojson/blob/main/docs/modules.html
Incrementally convert a TCX document to GeoJSON. The first argument, `doc`, must be a TCX document as an XML DOM - not as a string.
```APIDOC
## tcxGen
### Description
Incrementally convert a TCX document to GeoJSON. The first argument, `node`, must be a TCX document as an XML DOM - not as a string.
### Method
Not specified (likely a function call)
### Endpoint
Not applicable (this is a library function)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **Generator** (generator) - A generator yielding GeoJSON Feature objects.
#### Response Example
```javascript
// Example of iterating through the generator
for (const feature of tcxGen(xmlDoc)) {
console.log(feature);
}
```
```
--------------------------------
### Stream GPX Features with Generator
Source: https://context7.com/tmcw/togeojson/llms.txt
Uses the gpxGen generator to process GPX features incrementally. This approach is memory-efficient for large GPS files, allowing iteration over tracks, routes, and waypoints one by one.
```javascript
const tj = require("@tmcw/togeojson");
const { DOMParser } = require("@xmldom/xmldom");
const fs = require("fs");
const gpxString = fs.readFileSync("multi_day_hike.gpx", "utf8");
const gpxDom = new DOMParser().parseFromString(gpxString, "text/xml");
for (const feature of tj.gpxGen(gpxDom)) {
if (feature.geometry.type === "LineString") {
console.log("Processing track segment");
} else if (feature.geometry.type === "Point") {
console.log(`Waypoint: ${feature.properties?.name}`);
}
}
```
--------------------------------
### KML Conversion API
Source: https://github.com/tmcw/togeojson/blob/main/docs/index.html
Methods for converting KML data into GeoJSON format.
```APIDOC
## kml(doc, options)
### Description
Converts a KML document into GeoJSON.
### Method
Function Call
### Parameters
#### Path Parameters
- **doc** (Document) - Required - The XML DOM object representing the KML file.
- **options** (KMLOptions) - Optional - Configuration options for the conversion.
### Response
#### Success Response (Object)
- **type** (string) - The GeoJSON feature collection.
```
--------------------------------
### tcx
Source: https://github.com/tmcw/togeojson/blob/main/docs/modules.html
Convert a TCX document to GeoJSON. The first argument, `doc`, must be a TCX document as an XML DOM - not as a string.
```APIDOC
## tcx
### Description
Convert a TCX document to GeoJSON. The first argument, `node`, must be a TCX document as an XML DOM - not as a string.
### Method
Not specified (likely a function call)
### Endpoint
Not applicable (this is a library function)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **FeatureCollection** (object) - A GeoJSON FeatureCollection object.
#### Response Example
```json
{
"type": "FeatureCollection",
"features": [
// ... GeoJSON features
]
}
```
```
--------------------------------
### Perform Generator-Based KML Conversion
Source: https://context7.com/tmcw/togeojson/llms.txt
Uses a generator function to process KML features one by one. This approach is memory-efficient and ideal for handling large datasets.
```javascript
const tj = require("@tmcw/togeojson");
const { DOMParser } = require("@xmldom/xmldom");
const fs = require("fs");
const kmlString = fs.readFileSync("large_dataset.kml", "utf8");
const kmlDom = new DOMParser().parseFromString(kmlString, "text/xml");
for (const feature of tj.kmlGen(kmlDom)) {
console.log(`Processing: ${feature.properties?.name}`);
if (feature.geometry?.type === "Point") {
const [lon, lat] = feature.geometry.coordinates;
console.log(` Location: ${lat}, ${lon}`);
}
}
```
--------------------------------
### Convert KML Preserving Folder Structure
Source: https://context7.com/tmcw/togeojson/llms.txt
Converts KML data into a nested tree structure that maintains the original folder hierarchy. This is useful for applications where organizational metadata is critical.
```javascript
const tj = require("@tmcw/togeojson");
const { DOMParser } = require("@xmldom/xmldom");
const fs = require("fs");
const kmlString = fs.readFileSync("organized.kml", "utf8");
const kmlDom = new DOMParser().parseFromString(kmlString, "text/xml");
const tree = tj.kmlWithFolders(kmlDom);
function processTree(node, depth = 0) {
if (node.type === "folder") {
console.log(" ".repeat(depth) + "Folder: " + node.meta.name);
node.children.forEach(child => processTree(child, depth + 1));
} else if (node.type === "Feature") {
console.log(" ".repeat(depth) + "Feature: " + node.properties?.name);
}
}
tree.children.forEach(child => processTree(child));
```
--------------------------------
### Convert KML to GeoJSON using toGeoJSON
Source: https://context7.com/tmcw/togeojson/llms.txt
Converts a parsed KML DOM into a standard GeoJSON FeatureCollection. This method supports various KML features including styles, timestamps, and extended data.
```javascript
const tj = require("@tmcw/togeojson");
const { DOMParser } = require("@xmldom/xmldom");
const fs = require("fs");
const kmlString = fs.readFileSync("locations.kml", "utf8");
const kmlDom = new DOMParser().parseFromString(kmlString, "text/xml");
const geojson = tj.kml(kmlDom);
console.log(JSON.stringify(geojson, null, 2));
const geojsonFiltered = tj.kml(kmlDom, { skipNullGeometry: true });
```
--------------------------------
### Convert KML Document to GeoJSON - JavaScript
Source: https://github.com/tmcw/togeojson/blob/main/docs/modules.html
Converts a KML document (provided as an XML DOM) into a GeoJSON FeatureCollection. It can optionally accept KMLOptions for customization. The output is a JavaScript object that can be stringified or used directly.
```javascript
import { kml } from "@tmcw/togeojson";
// Assuming 'kmlDom' is an XML Document object representing KML data
const geojsonData = kml(kmlDom, options);
console.log(JSON.stringify(geojsonData));
```
--------------------------------
### TCX Conversion API
Source: https://github.com/tmcw/togeojson/blob/main/docs/index.html
Methods for converting TCX data into GeoJSON format.
```APIDOC
## tcx(doc)
### Description
Converts a TCX document into GeoJSON.
### Method
Function Call
### Parameters
#### Path Parameters
- **doc** (Document) - Required - The XML DOM object representing the TCX file.
### Response
#### Success Response (Object)
- **type** (string) - The GeoJSON feature collection.
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.