OpenLayers6(7):矢量图层要素导出KML文件

1 版本

  • OpenLayers:6.14.1


2 相关配置

/**
FileSaver.js 在没有原生支持 saveAs() 的浏览器上实现了 saveAs() 接口。
FileSaver.js 是在客户端保存文件的解决方案,非常适合需要生成文件,
或者保存不应该发送到外部服务器的敏感信息的 web App。
*/

npm i file-saver

3 API说明

3.1 ol/format/KML

Openlayers中用于读/写KML格式数据的要素格式类,API如下:

  • readFeature:Read a single feature.
  • readFeatures:Read all features from a feature collection.
  • readName:Read the name of the KML.
  • readNetworkLinks:Read the network links of the KML.
  • readProjection:Read the projection from the source.
  • readRegion:Read the projection from the source.
  • writeFeatures:Encode an array of features as string.
  • writeFeaturesNode:Encode an array of features in the KML format as an XML node. GeometryCollections, MultiPoints, MultiLineStrings, and MultiPolygons are output as MultiGeometries.

3.2 saveAs

FileSaver.js中用于将数据保存到本地生成文件,示例如下(摘抄自网上):

import { saveAs } from 'file-saver';

FileSaver saveAs(Blob/File/Url, optional DOMString filename, optional Object { autoBom })


var FileSaver = require('file-saver');

// 保存文本
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "hello world.txt");

// 保存画布(canvas)
var canvas = document.getElementById("my-canvas"), ctx = canvas.getContext("2d");
// draw to canvas...
canvas.toBlob(function(blob) {
    saveAs(blob, "pretty image.png");
});

// 保存网址
FileSaver.saveAs("https://httpbin.org/image", "image.jpg");
// 保存文件
var file = new File(["Hello, world!"], "hello world.txt", {type: "text/plain;charset=utf-8"});

saveAs(file);

4 导出KML方法

export function exportKML(features, name, isWGS84 = false) {
    let features1 = [];
    
    // Circle 不是标准图形,导出会报错
    features.forEach(f => {
        if (!(f.getGeometry() instanceof Circle)) {
            features1.push(f);
        }
    });

    // 需要以WGS84坐标导出
    if (!isWGS84) {
        features1.forEach(f => {
            f.getGeometry().transform("EPSG:3857", "EPSG:4326");
        });
    }
    const kmlXML = new KML().writeFeaturesNode(features1);

    // 导出之后将图形转回Web莫卡托投影
    if (!isWGS84) {
        features1.forEach(f => {
            f.getGeometry().transform("EPSG:4326", "EPSG:3857");
        });
    }

    // 最后使用saveAs导出成本地文件
    const str = new XMLSerializer().serializeToString(kmlXML)
    saveAs(new Blob([str], {
        type: 'text/plain;charset=utf-8'
    }), `${name}.kml`);

}

5 效果图

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

碰碰qaq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值