openlayers官方教程(九)Vector Data——Downloading features

Downloading features

在上传和编辑数据之后,我们想要用户来下载我们的结果。我们需要将数据序列化为GeoJSON格式,并且创建

用于在浏览器中触发保存文件的downLoad属性。同时在地图上添加一个按钮,让用户可以清除已有要素重新开始。

首先,我们来添加按钮,把下面代码添加到index.html的map-container中:

<div id="tools">
  <a id="clear">Clear</a>
  <a id="download" download="features.json">Download</a>
</div>

再来用CSS控制按钮的样式,增加如下代码到index.html的<style>中:

#tools {
  position: absolute;
  top: 1rem;
  right: 1rem;
}
#tools a {
  display: inline-block;
  padding: 0.5rem;
  background: white;
  cursor: pointer;
}

清除要素很简单,矢量数据源有一个source.clear()方法。我们要通过点击clear来调用方法,所以在main.js中添加按钮的监听:

const clear = document.getElementById('clear');
clear.addEventListener('click', function() {
  source.clear();
});

将要素数据序列化为GeoJSON格式,我们想下载按钮在任何编辑时刻都有效,我们将在每次change的时候序列化features,同时生成data URI。

const format = new GeoJSON({featureProjection: 'EPSG:3857'});
const download = document.getElementById('download');
source.on('change', function() {
  const features = source.getFeatures();
  const json = format.writeFeatures(features);
  download.href = 'data:text/json;charset=utf-8,' + json;
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值