mars3d将矢量数据保存为kml

 

在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
}

你可能感兴趣的:(Mars3d,vue,app,javascript,前端,vue.js)