geojson-to-kml (KML 格式转换工具)
一个 简单、轻量、健壮 的 JavaScript / TypeScript 库,用于将 GeoJSON 数据转换为 KML (Keyhole Markup Language) 格式。
本库不仅支持基础的几何转换,还完整支持了 Mapbox SimpleStyle 规范 ,可以将 GeoJSON 中的样式属性(如 marker-color、stroke 等)转换为 KML 的样式定义。
✨ 特性
- 🚀 零依赖:基于轻量级逻辑实现,无沉重依赖。
- 🛡️ 类型安全 :原生 TypeScript 支持,完美适配
geojson类型定义。 - 🎨 样式支持:支持 Mapbox SimpleStyle,自动生成 KML Style 标签。
- 📊 数据保留 :GeoJSON 的
properties会自动转换为 KML 的ExtendedData。 - 🧩 全类型支持:涵盖所有 Geometry、Feature、FeatureCollection。
- 🌲 Tree Shaking:现代化 ESM 导出,支持按需引入。
📦 安装
bash
# npm
npm install @giszhc/geojson-to-kml
或
bash
# pnpm
pnpm add @giszhc/geojson-to-kml
🚀 快速上手
基础用法
TypeScript
ts
import tokml from '@giszhc/geojson-to-kml';
const geojson = {
type: 'Point',
coordinates: [120.123, 30.456]
};
const kml = tokml(geojson);
console.log(kml);
// 输出包含 <Placemark><Point>... 的 XML 字符串
带样式的转换 (SimpleStyle)
TypeScript
ts
const feature = {
type: 'Feature',
properties: {
name: '我的位置',
'marker-color': '#ff0000',
'stroke': '#00ff00',
'stroke-width': 3
},
geometry: {
type: 'Point',
coordinates: [120, 30]
}
};
const kml = tokml(feature, {
simplestyle: true, // 开启样式转换
name: 'name' // 指定使用哪个属性作为节点名称
});
🛠️ API 参数说明
tokml(geojson: GeoJSON, options?: TokmlOptions): string
| 参数名 | 类型 | 描述 | 默认值 |
|---|---|---|---|
documentName |
string |
KML <Document> 节点的名称 |
undefined |
documentDescription |
string |
KML <Document> 节点的描述 |
undefined |
name |
string |
从 properties 中提取哪个字段作为 <name> |
'name' |
description |
string |
从 properties 中提取哪个字段作为 <description> |
'description' |
simplestyle |
boolean |
是否将 Mapbox 样式属性转换为 KML 样式 | false |
timestamp |
string |
从 properties 中提取哪个字段作为 <TimeStamp> |
'timestamp' |
🎨 支持的样式属性 (SimpleStyle)
当开启 simplestyle: true 时,以下 GeoJSON 属性将被识别并转换:
| 属性名 | 描述 | 示例 |
|---|---|---|
marker-color |
标记点的颜色 (Hex) | #ff0000 |
marker-size |
标记点大小 (small, medium, large) |
large |
marker-symbol |
标记点图标符号 | bus, star |
stroke |
线条或多边形边界颜色 | #0000ff |
stroke-opacity |
线条透明度 (0.0 - 1.0) | 0.5 |
stroke-width |
线条宽度 (像素) | 2 |
fill |
多边形填充颜色 | #00ff00 |
fill-opacity |
填充透明度 (0.0 - 1.0) | 0.3 |
⚠️ 注意事项
- 坐标系 :KML 官方规范要求使用 WGS84 (EPSG:4326) 经纬度。转换前请确保您的 GeoJSON 坐标正确。
- 数据类型 :所有的
properties都会被放入<ExtendedData>中,这有助于在 Google Earth 等软件中查看完整的业务数据。 - 命名空间 :生成的 KML 默认包含
xmlns="http://www.opengis.net/kml/2.2"。
完结,撒花✿✿ヽ(°▽°)ノ✿