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`);
}