mars3d将矢量数据保存为kml

178 篇文章 2 订阅
160 篇文章 0 订阅
文章介绍了在3D场景应用中如何使用JavaScript库kml-geojson将矢量数据转换为KML格式。通过提供的`saveGeoJSON2Kml`函数,可以设置KML文档的元信息并进行转换。同时,`clone`函数用于深拷贝对象,确保转换过程中的数据完整性和避免死循环。
摘要由CSDN通过智能技术生成

 

在3d场景的应用中经常需要将矢量数据保存为kml格式,下面来看一下如何实现

首先安装 kml-geojson这个库:

npm i kml-geojson -S

代码如下:
(说明:如果是vite项目,还需要将kml-geojson配置为预构建)

function saveGeoJSON2Kml(geojson: string, options: any): any {
  const geojsonObject = clone(geojson, null, null)
 
  const kml = toKml(geojsonObject, {
    name: "Mars3D标绘数据",
    documentName: "Mars3D标绘数据文件",
    documentDescription: "标绘数据 by mars3d.cn",
    simplestyle: true,
    ...options
  })
  return kml
}

function clone(obj: any, removeKeys: any, level: any): any {
  // 避免死循环,拷贝的层级最大深度
  if (level == null) {
    level = 9
  }
  if (removeKeys == null) {
    removeKeys = ["_layer"]
  }

  if (obj === null || typeof obj !== "object") {
    return obj
  }

  // Handle Date
  if (isDate(obj)) {
    const copy = new Date()
    copy.setTime(obj.getTime())
    return copy
  }

  // Handle Array
  if (isArray(obj) && level >= 0) {
    const copy = []
    for (let i = 0, len = obj.length; i < len; i++) {
      copy[i] = clone(obj[i], removeKeys, level - 1)
    }
    return copy
  }

  // Handle Object
  if (typeof obj === "object" && level >= 0) {
    try {
      const copy: any = {}
      for (const attr in obj) {
        if (typeof attr === "function") {
          continue
        }
        if (removeKeys.indexOf(attr) !== -1) {
          continue
        }

        if (obj.hasOwnProperty(attr)) {
          copy[attr] = clone(obj[attr], removeKeys, level - 1)
        }
      }
      return copy
    } catch (e) {
      console.log(e)
    }
  }
  return obj
}
function isArray(obj: any) {
  if (typeof Array.isArray === "function") {
    return Array.isArray(obj)
  } else {
    return Object.prototype.toString.call(obj) === "[object Array]"
  }
}
function isDate(obj: any) {
  return typeof obj === "object" && obj.constructor === Date
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值