How to Import KML Files into GeoLibre for Client-Side Processing

GeoLibre converts KML and KMZ files into GeoJSON FeatureCollections entirely within the browser using the parseKmlText function in apps/geolibre-desktop/src/lib/kml.ts, eliminating server dependencies while preserving original styling.

The opengeos/GeoLibre project provides a zero-dependency KML parser designed for client-side geospatial workflows. When you import KML files into GeoLibre, the XML content processes directly through the DOMParser API, making the library ideal for offline field applications and privacy-sensitive mapping tasks.

Understanding GeoLibre's KML Parser Architecture

GeoLibre processes KML through a dedicated parsing module that transforms XML documents into native GeoJSON structures. This architecture ensures that vector data, ground overlays, and 3D models remain manipulable within the application's Zustand-based state management.

Core Parser Functions in kml.ts

The primary entry point for KML import is apps/geolibre-desktop/src/lib/kml.ts, which exposes three critical functions:

  • parseKmlText – Converts XML text into a GeoJSON FeatureCollection, translating <Placemark> elements into features and <Style> definitions into simplestyle-spec properties (e.g., stroke, fill, marker-color).
  • parseKmlGroundOverlays – Extracts <GroundOverlay> elements into KmlGroundOverlay objects containing coordinates, opacity, draw order, and optional time bounds.
  • parseKmlModels – Parses embedded <Model> elements (COLLADA meshes) for 3D visualization.

The Tauri-IO Bridge

When running in the Tauri desktop environment, file I/O flows through apps/geolibre-desktop/src/lib/tauri-io.ts. This bridge decodes raw file bytes to UTF-8 strings before routing them to the parser, ensuring consistent handling across browser and desktop contexts.

Step-by-Step KML Import Workflow

Importing KML data into GeoLibre follows a consistent pipeline from file acquisition to layer rendering.

Step 1: Reading the KML File

For web applications, use the standard FileReader API to extract text content from user-selected files. In Tauri contexts, the IO bridge handles binary decoding automatically.

Step 2: Parsing Vector Data

Feed the XML string to parseKmlText to generate a GeoJSON FeatureCollection. Each <Placemark> becomes a feature with preserved styling metadata compatible with MapLibre's rendering engine.

Step 3: Extracting Raster and 3D Assets

Optionally process ground overlays and 3D models by calling parseKmlGroundOverlays and parseKmlModels on the same source text. These return specialized objects for image sources and mesh layers respectively.

Step 4: Adding Layers to the Store

Pass the resulting GeoJSON to the store's addGeoJsonLayer method. Ground overlays integrate as MapLibre image sources, while the parser's simplestyle translation ensures features render with their original colors and stroke weights.

Implementation Examples

Handling File Uploads in React

Implement drag-and-drop or file input handlers using the following pattern:

import { parseKmlText, parseKmlGroundOverlays } from 'apps/geolibre-desktop/src/lib/kml';
import { useStore } from './store';

function handleKmlUpload(e: React.ChangeEvent<HTMLInputElement>) {
  const file = e.target.files?.[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = async () => {
    const text = reader.result as string;
    try {
      const featureCollection = parseKmlText(text);
      store.addGeoJsonLayer(featureCollection, { name: file.name });

      const overlays = parseKmlGroundOverlays(text);
      overlays.forEach(overlay => store.addGroundOverlay(overlay));
    } catch (err) {
      console.error('Invalid KML:', err);
    }
  };
  reader.readAsText(file);
}

Importing KML from Remote URLs

Fetch and parse external KML resources programmatically:

async function importKmlFromUrl(url: string) {
  const response = await fetch(url);
  const kmlText = await response.text();

  const featureCollection = parseKmlText(kmlText);
  store.addGeoJsonLayer(featureCollection, { name: 'Remote KML' });

  const overlays = parseKmlGroundOverlays(kmlText);
  overlays.forEach(overlay => store.addGroundOverlay(overlay));
}

Preserving KML Styling with Simplestyle-Spec

GeoLibre's parser automatically translates Google Earth styling into simplestyle-spec keys. The parseKmlText function inspects <Style> and <StyleMap> elements to populate properties like stroke for line colors, fill for polygon interiors, and marker-color for point symbols. This translation occurs entirely client-side using the DOMParser API, ensuring zero data leakage to external servers while maintaining visual fidelity with the original KML rendering.

Working with Advanced KML Features

Beyond standard vector geometry, GeoLibre handles complex KML constructs through specialized parsers.

Ground Overlays

Raster images anchored to geographic coordinates extract as KmlGroundOverlay objects. These include latitude/longitude bounds, rotation, opacity settings, and temporal bounds for time-enabled datasets. The store method addGroundOverlay converts these into MapLibre image sources with proper georeferencing.

3D Models

Embedded COLLADA meshes within <Model> tags parse through parseKmlModels, returning structural data consumed by apps/geolibre-desktop/src/lib/kml-model-layer.ts. This enables client-side rendering of textured 3D structures without external processing pipelines.

Summary

  • GeoLibre processes KML files entirely in the browser using parseKmlText in apps/geolibre-desktop/src/lib/kml.ts, requiring no server infrastructure.
  • The parser converts <Placemark> elements to GeoJSON features while preserving styles as simplestyle-spec properties.
  • Raster ground overlays and 3D models extract via parseKmlGroundOverlays and parseKmlModels respectively.
  • The Tauri desktop wrapper utilizes apps/geolibre-desktop/src/lib/tauri-io.ts to bridge native file system access to the parser.
  • Resulting layers integrate into the Zustand store through addGeoJsonLayer and specialized overlay methods.

Frequently Asked Questions

Does GeoLibre require a server to parse KML files?

No. GeoLibre's parser operates entirely client-side using the browser's native DOMParser API. The parseKmlText function processes XML strings directly within apps/geolibre-desktop/src/lib/kml.ts, making it suitable for offline field applications and privacy-sensitive workflows where data must not leave the local device.

What KML styling elements are preserved during import?

The parser translates <Style> and <StyleMap> definitions into simplestyle-spec properties including stroke for line colors, fill for polygon interiors, and marker-color for point features. This ensures visual consistency with Google Earth while remaining compatible with MapLibre's default style processors.

Can GeoLibre handle KMZ files in addition to KML?

Yes. While the parser itself processes decoded text, the Tauri-IO bridge in apps/geolibre-desktop/src/lib/tauri-io.ts handles the binary decoding required for KMZ archives. The system extracts the embedded KML document before routing it to parseKmlText, maintaining the same client-side processing guarantees.

How does GeoLibre handle 3D models embedded in KML?

The parseKmlModels function extracts COLLADA meshes from <Model> elements, returning structured data consumed by apps/geolibre-desktop/src/lib/kml-model-layer.ts. This enables native rendering of textured 3D buildings and structures within the MapLibre canvas without requiring external 3D processing services.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →