在3d场景的应用中经常需要将矢量数据保存为kml格式,下面来看一下如何实现
    首先安装 kml-geojson这个库

    1. npm i kml-geojson -S

    代码如下

    1. function saveGeoJSON2Kml(geojson: string, options: any): any {
    2. const geojsonObject = clone(geojson, null, null)
    3. const kml = toKml(geojsonObject, {
    4. name: "Mars3D标绘数据",
    5. documentName: "Mars3D标绘数据文件",
    6. documentDescription: "标绘数据 by mars3d.cn",
    7. simplestyle: true,
    8. ...options
    9. })
    10. return kml
    11. }
    12. function clone(obj: any, removeKeys: any, level: any): any {
    13. // 避免死循环,拷贝的层级最大深度
    14. if (level == null) {
    15. level = 9
    16. }
    17. if (removeKeys == null) {
    18. removeKeys = ["_layer"]
    19. }
    20. if (obj === null || typeof obj !== "object") {
    21. return obj
    22. }
    23. // Handle Date
    24. if (isDate(obj)) {
    25. const copy = new Date()
    26. copy.setTime(obj.getTime())
    27. return copy
    28. }
    29. // Handle Array
    30. if (isArray(obj) && level >= 0) {
    31. const copy = []
    32. for (let i = 0, len = obj.length; i < len; i++) {
    33. copy[i] = clone(obj[i], removeKeys, level - 1)
    34. }
    35. return copy
    36. }
    37. // Handle Object
    38. if (typeof obj === "object" && level >= 0) {
    39. try {
    40. const copy: any = {}
    41. for (const attr in obj) {
    42. if (typeof attr === "function") {
    43. continue
    44. }
    45. if (removeKeys.indexOf(attr) !== -1) {
    46. continue
    47. }
    48. if (obj.hasOwnProperty(attr)) {
    49. copy[attr] = clone(obj[attr], removeKeys, level - 1)
    50. }
    51. }
    52. return copy
    53. } catch (e) {
    54. console.log(e)
    55. }
    56. }
    57. return obj
    58. }
    59. function isArray(obj: any) {
    60. if (typeof Array.isArray === "function") {
    61. return Array.isArray(obj)
    62. } else {
    63. return Object.prototype.toString.call(obj) === "[object Array]"
    64. }
    65. }
    66. function isDate(obj: any) {
    67. return typeof obj === "object" && obj.constructor === Date
    68. }

    如果是vite项目,还需要将kml-geojson配置为预构建